package com.application.Controller;

import it.unipr.ce.dsg.s2p.message.Payload;
import it.unipr.ce.dsg.s2p.org.json.JSONException;
import it.unipr.ce.dsg.s2p.org.json.JSONObject;
import it.unipr.ce.dsg.s2p.sip.Address;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Iterator;

import org.w3c.dom.Document;

import ReadWriteXML.CMember;
import ReadWriteXML.CQuestion;
import ReadWriteXML.CUsingQuestionList;
import ReadWriteXML.ReadXML;
import ReadWriteXML.WriteXML;
import android.app.Activity;
import android.app.Notification;
import android.os.Handler;
import android.util.Log;

import com.application.Activity.FrmChapter;
import com.application.Activity.FrmChatGroup;
import com.application.Activity.FrmChatInvite;
import com.application.Activity.FrmChatPeer;
import com.application.Activity.FrmConversation;
import com.application.Activity.FrmDoFeedback;
import com.application.Activity.FrmInviteGroupChat;
import com.application.Activity.FrmPart;
import com.application.Activity.FrmShowResultOfTest;
import com.application.Activity.FrmSubject;
import com.application.Activity.FrmTabActivity;
import com.application.Activity.FrmViewExercise;
import com.application.Activity.frmBieuQuyetMoiRoiNhom;
import com.application.Activity.frmChatPeerActivity;
import com.application.Activity.frmMyConversation;
import com.application.Activity.frmTreeNodeActivity;
import com.application.Activity.tabActivity;
import com.application.Activity.trucActivity;
import com.application.DTO.AccountDTO;
import com.application.DTO.ChapterDTO;
import com.application.DTO.DetailLearningDTO;
import com.application.DTO.ExercisesGroupDTO;
import com.application.DTO.FeelChoiceDTO;
import com.application.DTO.FeelTypeDTO;
import com.application.DTO.PartDTO;
import com.application.DTO.RoleDTO;
import com.application.DTO.SubjectDTO;
import com.application.DTO.TeacherDTO;
import com.application.DataProvider.ChapterDAO;
import com.application.DataProvider.DetailLearningDAO;
import com.application.DataProvider.FeelChoiceDAO;
import com.application.DataProvider.FeelTypeDAO;
import com.application.DataProvider.JoinSubjectClassDAO;
import com.application.DataProvider.PartDAO;
import com.application.DataProvider.SubjectDAO;
import com.application.DataProvider.TeacherDAO;
import com.application.DataProvider.UpdateListDAO;
import com.application.DataProvider.UsingFeelListDAO;
import com.application.Message.PingMessage;
import com.application.Network.NetworkLayer;
import com.application.Network.Protocol;
import com.application.PhanQuyen.Quyen;
import com.application.TextNode.INodeText;
import com.application.Tree.INode;

public class NetworkController {
	//=====truc
	private static int nodeCurrenIndex = 0;
	
	public static Handler handler = new Handler();
	public static Address sender;
	public static String thanhLapNhomIP="";
	// chat rieng	
	private static boolean isConnected=false;
	
	//An
	private static String groupName = "";
	
	//====end truc====
	public static NetworkLayer _peer = null;
	private static boolean _isSaveMessage = false;
	private static int _isLogin = 0;
	private static String _userName = null;
	private static String _fullName = null;
	private static int _idClass = 0;
	private static String _ipHost = null;
	private final static String SEPARATOR1 = "##";
	private final static String SEPARATOR = "/";
	private static boolean _isOffline = false;
	private static int _idLearner = 0;
	private static String _ipUser ;
	private static String _userNameTeacher;

	private static Runnable _runUpdateMsg;
	private static Runnable _runUpdateMsgGroup;
	private static Runnable _runUpdateMsgInvite;
	private static Runnable _runUpdateChapter;
	private static Runnable _runUpdatePart;
	private static Runnable _runUpdateUserList;

	private static boolean _isDoExericseGroup = false;
	private static boolean _isDoSearchGroup = false;
	private static boolean _isWriteNeighborsList = false;
	private static boolean _isTeamLeader = false;
	private static int _timedotest = 0;
	public static int PORT_NUMBER_BEGIN = 5559;
	public static int PORT_NUMBER_CURRENT = 5559;
	public static ArrayList<Integer> ARRAY_PORT = new ArrayList<Integer>();
	public static ArrayList<Thread> ARRAY_THREAD = new ArrayList<Thread>();
	
	
	///===================TRUC==========================
	public static String getGroupName() {
		return groupName;
	}

	public static void setGroupName(String groupName) {
		NetworkController.groupName = groupName;
	}
	//End

	/**
	 * Phú Gửi lời mời vào nhóm
	 * 
	 * @param toAddress
	 *            : Địa chỉ muốn mời
	 * @param groupName
	 *            : Tên nhóm của mình
	 * @param msg
	 *            : Lời nhắn(mời)
	 * @return
	 */

	public static boolean sendGroupInvite(Address toAddress, String groupName, String msg) {

		Log.d("Phu", " vao ham sendGroupInvite: groupName:"+groupName+ " msg:"+msg);
		
			PingMessage message = new PingMessage(_peer.getPeerDescriptor());
			message.setType(Protocol.GROUP_INVITE);
			Payload payload = new Payload();
			payload.addParam(Protocol.GROUP_INVITE_DATA_GROUP_NAME, groupName);
			payload.addParam(Protocol.GROUP_INVITE_DATA_MSG, msg);
			message.setPayload(payload);
			_peer.send(toAddress, message);
			Log.d("Phu", "Da send sendGroupInvite to: " + toAddress.getHost() + ":" + toAddress.getPort());
		
		return true;
	}

	public static boolean sendDongYVaoNhom(Address toAddress) {
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
		msg.setType(Protocol.GROUP_INVITE_REPLY_YES);
		_peer.send(new Address(toAddress), msg);
		Log.d("Phu", "Da send sendDongYVaoNhom to:" + toAddress.getHost() + ":" + toAddress.getPort());
		return true;
	}

	public static boolean sendKhongChoVaoNhom(Address toAddress) {
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
		msg.setType(Protocol.GROUP_INVITE_NO);
		_peer.send(new Address(toAddress), msg);
		Log.d("Phu", "Da send sendKhongChoVaoNhom to:" + toAddress.getHost() + ":" + toAddress.getPort());
		return true;
	}

	public static boolean sendChoVaoNhom(Address toAddress) {
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
		msg.setType(Protocol.GROUP_INVITE_YES);
		_peer.send(new Address(toAddress), msg);
		Log.d("Phu", "Da send sendChoVaoNhom to:" + toAddress.getHost() + ":" + toAddress.getPort());
		return true;

	}

	public static boolean sendSetRole(Address toAddress, ArrayList<RoleDTO> roleList) {
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());

		Payload payload = new Payload();
		payload.addParam("DATA", RoleDTO.toStringList(roleList));
		msg.setType(Protocol.SET_ROLE);
		msg.setPayload(payload);
		_peer.send(toAddress, msg);
		Log.d("Phu", "Da send sendSetRole to:" + toAddress.getHost() + ":" + toAddress.getPort());
		return true;
	}

	public static boolean sendJoinGroup(Address toAddress, String userName, String fullName) {
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());

		Payload payload = new Payload();
		payload.addParam(Protocol.MEMBER_FULL_NAME, fullName);
		payload.addParam(Protocol.MEMBER_USER_NAME, userName);

		msg.setType(Protocol.JOIN_GROUP);
		msg.setPayload(payload);
		_peer.send(toAddress, msg);
		Log.d("Phu", "Da send sendJoinGroup to:" + toAddress.getHost() + ":" + toAddress.getPort());
		return true;
	}

	public static boolean sendUpdateMember(Address toAddress, CMember member) {
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());

		Payload payload = new Payload();
		payload.addParam(Protocol.UPDATE_MEMBER_LIST, member.toParse());
		msg.setType(Protocol.UPDATE_MEMBER_LIST);
		msg.setPayload(payload);
		_peer.send(toAddress, msg);
		Log.d("Phu", "Da send sendUpdateMember to:" + toAddress.getHost() + ":" + toAddress.getPort());
		return true;
	}

	public static boolean sendMemberList(Address toAddress, ArrayList<CMember> memberList) {

		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
		Payload payload = new Payload();
		payload.addParam(Protocol.MEMBER_LIST, CMember.toParseList(memberList));
		msg.setType(Protocol.MEMBER_LIST);
		msg.setPayload(payload);
		_peer.send(toAddress, msg);
		Log.d("Phu", "Da send sendMemberList to:" + toAddress.getHost() + ":" + toAddress.getPort() + "/data: "
				+ CMember.toParseList(memberList));
		return true;
	}

	public static boolean sendStartGroup(Address toAddress) {
		Log.d("Phu", "Da send sendMemberList to:" + toAddress.toString());
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
		msg.setType(Protocol.START_GROUP);
		_peer.send(toAddress, msg);
		return true;
	}

	public static boolean sendAddTreeNode(Address toAddress,long parentID, INode node) {
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
		Payload payload = new Payload();
		payload.addParam(Protocol.ADD_NODE, node.toParse());
		payload.addParam(Protocol.TREENODE_ID, parentID+"");
		msg.setType(Protocol.ADD_NODE);
		msg.setPayload(payload);
		_peer.send(toAddress, msg);
		Log.d("Phu", "Da send sendAddTreeNode to:" + toAddress.toString()+" parentID="+parentID);
		return true;
	}
	public static boolean sendUpdateNodeText(Address toAddress, long id, String text){
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
		Payload payload = new Payload();
		payload.addParam(Protocol.TREENODE_ID, id+"");
		payload.addParam(Protocol.TREE_TEXT, text);		
		msg.setType(Protocol.UPDATE_NODE_TEXT);
		msg.setPayload(payload);
		_peer.send(toAddress, msg);
		Log.d("Phu", "Da send sendUpdateNodeText to:" + toAddress.toString());
		return true;
	}
	public static boolean sendDeleteTreeNode(Address toAddress, long id){
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
		Payload payload = new Payload();
		payload.addParam(Protocol.TREENODE_ID,id+"");
		msg.setType(Protocol.DELETE_NODE_TREE);
		msg.setPayload(payload);
		_peer.send(toAddress, msg);
		Log.d("Phu", "Da send sendDeleteTreeNode to:" + toAddress.toString());
		return true;
		
	}
	public static ArrayList<CMember> getMemberList() {
		ArrayList<CMember> memberList = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
		Log.d("Phu", "NetworkController. getMemberList size:" + memberList.size());
		return memberList;
	}

	public static boolean sendPing(Address toAddress){		
		PingMessage msg=new PingMessage(_peer.getPeerDescriptor());
		msg.setType(Protocol.PING_MSG);
		_peer.send(toAddress, msg);
		Log.d("Phu","sendPing to: "+toAddress.toString());
		return true;
	}
	public static boolean sendPingReply(Address toAddress){
		PingMessage msg=new PingMessage(_peer.getPeerDescriptor());
		msg.setType(Protocol.PING_MSG_REPLY);
		_peer.send(toAddress, msg);
		Log.d("Phu","sendPingReply to: "+toAddress.toString());
		return true;
	}
	public static boolean sendTreeText(Address toAddress, String data){
		PingMessage msg=new PingMessage(_peer.getPeerDescriptor());
		Payload p=new Payload();
		p.addParam(Protocol.TREE_TEXT, data);
		msg.setPayload(p);
		msg.setType(Protocol.TREE_TEXT);
		_peer.send(toAddress, msg);
		Log.d("Phu","sendTreeText to: "+toAddress.toString());
		return true;
	}
	
	public static boolean sendUpdateTree(Address toAddress){
		PingMessage msg=new PingMessage(_peer.getPeerDescriptor());
		msg.setType(Protocol.UPDATE_TREE);
		_peer.send(toAddress, msg);
		Log.d("Phu","sendUpdateTree to: "+toAddress.toString());
		return true;
	}
	//end phu
	// ========================================truc===============================================

	public static void ReLoadTab(){
		handler.post(new Runnable() {
			
			@Override
			public void run() {
				ActivityController.ReLoadTabTree();
			}
		});
	}
	
	public static void ShowMessageNoticeTAB(final String message) {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				ActivityController.ShowMessageTAB(message);
			}
		});
	}
	//========tree=======
	public static void ShowMessageNoticeOnTree(final String message) {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				ActivityController.ShowMessageOnTree(message);
			}
		});
	}
	//===enD tree======
	// chat rieng
		public static void ShowChatPeer(final String ipSender, final String userName) {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.ShowChatPeer(ipSender, userName);
			}
		});
	}

	public static void ShowChatPeerNonParamater() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.ShowChatPeerNonParamater();
			}
		});
	}

	public static void UpdateMessageInConversation(String keychat, String mess, String ip) {
		final ArrayList<Object> message = new ArrayList<Object>();
		message.add(keychat);
		message.add(mess);
		// message.add(type);
		message.add(ip);
		// message.add(fullName);
		ActivityController.handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// frmMyConversation.receiveMessage(message);
			}
		});
	}

	public static void ReceiveMessageChatPeer(JSONObject params, Address sender) throws IOException {
		Log.d("Phu", "vao ReceiveMessageChatPeer");
		if (_peer.getAccount().getRuleById(7) != null && _peer.getAccount().getRuleById(7).getReceive()) {
			Iterator<String> iter = params.keys();
			while (iter.hasNext()) {
				Log.d("Phu", "vao while ReceiveMessageChatPeer");
				String key = iter.next();
				String s = null;
				try {
					s = params.get(key).toString();
					// username/text/ip
					Log.d("Phu", "s=" + s);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Log.d("Phu", "Key " + key);
				if (key.equals("Message")) {
					Log.d("Phu", "key la " + key);
					String[] sTemp = s.split("/");
					final String acc = sTemp[0];
					final String ipsend = sTemp[2];
					String mess = sTemp[1];// getMessage(sTemp);
					Log.d("Phu", "controller username: " + acc);
					Log.d("Phu", "controller ip send: " + ipsend);
					Log.d("Phu", "Sender ip=" + sender.getURL());
					Log.d("Phu", "controller mess: " + mess);
					// ---------tien hanh ghi file----------

					// ReadWriteFileController.writeTXT("Peer_"+acc+"_Content.txt",
					// fullName + ":" + mess);
					ReadWriteFileController.writeTXTPath(ReadWriteFileController.DIRECTORYCHATPEER + "Peer_" + acc
							+ ".txt", acc + ":" + mess);
					Log.d("Phu", "da ghi file xong");

					String userNameChatting = frmChatPeerActivity._FriendChatting;
					Log.d("Phu", "=====================username dang chat=" + userNameChatting);

					if (userNameChatting == null) {
						frmChatPeerActivity._FriendChatting = acc;
						ShowChatPeer(ipsend, acc);
					} else {
						Log.d("Phu", "----------Acc = " + acc);
						Log.d("Phu", "----------chatting = " + userNameChatting);
						if (userNameChatting.equals(acc)) {// la dang chat voi
															// minh
							Log.d("Phu", "dang chat together");
							handler.post(_runUpdateMsg);
							// init_runnableUpdateMsg();
							// handler.post(frmChatPeerActivity._runUpdateMsg);
							Log.d("Phu", "run update message xong");
						} else {// minh dang chat voi nguoi khac
							Log.d("Phu", "dang chat voi nguoi khac");
							// show notification co sender gui tin nhan
							NotificationController.sendNotification(ActivityController.getPeerActivity()
									.getBaseContext(), frmChatPeerActivity.class, "Nhận tin nhắn của " + acc, mess,
									Notification.DEFAULT_SOUND, acc, ipsend);
						//	NetworkController.CloseChatPeerActivity();
						}
					}
					// chay wa rui ok

					Log.d("Phu", "networkcontroller vao conversation nhan tin nhan");
					// ActivityController.hander.post(new Runnable() {
					//
					// @Override
					// public void run() {
					// // TODO Auto-generated method stub
					// frmConversation.receiveMessage(message);
					// }
					// });

					// frmMyConversation.mess=message;
					// handler.post(frmMyConversation.raReceiveMessage);

					Log.d("Phu", "conversation nhan tin nhan xong");
				}
			}
		} else {
			Log.d("Phu", "gui phan hoi ko chat net layer");
			NetworkController.ShowMessageNoticeTAB("Bạn không có quyền nhận tin nhắn trò chuyện.");
			NetworkController.GuiPhanHoiKhongCoQuyenChat(sender, _peer.getAccount().get_Username());
		}
	}

	public static void ShowChatConversation() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.ShowChatConversation();
			}
		});
	}

	// ====end chat rieng

	

	// Quyền : 0:Chat, 1:Cam ngkhac noi, 2: moi nguoi khac ra khoi nhom
	public static void ShowMessageNotice(final String message) {
//		handler.post(new Runnable() {
//
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub

				ActivityController.ShowMessage(message);
//			}
//		});
	}

	public static void ShowMessageChat(final String content, final String Address) {
//		handler.post(new Runnable() {
//			@Override
//			public void run() {
//				ActivityController.ShowChatMessage(content, Address);
//			}
//		});
		trucActivity.chatMessage=content;
		trucActivity.addressFriend=Address;
		handler.post(trucActivity.showChatMessage);
	}

	public static void HienThiTinNhanChatRieng() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				// ActivityController.HienThiTinNhanChatRieng();
			}
		});
	}

	public static void DislayVoteKickMember() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.DislayKickMember();
			}
		});
	}

	public static void DislayResultVoteKick() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.ShowResultVote();
			}
		});
	}

	public static void doEndTimeKick() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.DoEndTime();
			}
		});
	}

	// quyen 6
	public static void GuiYeuCauNgungThaoLuan(final Address toAdd, int time) {
		Log.d("Phu", "vao Controller ngung noi");

		
		PingMessage mess = new PingMessage(_peer.getPeerDescriptor());
		mess.setType(Protocol.STOP_TALKING_ONE_MEMBER);
		Payload pl = new Payload();
		pl.addParam("TimeStopTalk", time);
		mess.setPayload(pl);
		// String message="Ban da bi ngung noi";
		_peer.send(new Address(toAdd), mess);

		Log.d("Phu", "gui yeu cau ngung noi");
	}

	public static void GuiChoPhepThaoLuan(Address toAddress) {
		Log.d("Phu", "vao Controller cho phep noi");
		// boolean YourRule = _peer.getAccount().getRuleById(6).getSend();
		// if (YourRule) {
		Log.d("Phu", "vao if cho noi");
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.ACCEPT_TALKING_ONE_MEMBER);
		_peer.send(new Address(toAddress), message);
		Log.d("Phu", "gui yeu cau cho noi");
		// } else {
		// Log.d("Phu", "ko get dc quyen");
		// NetworkController.ShowMessageNotice(Protocol.NON_RULE_MESSAGE);
		// }
	}

	public static void NhanYeuCauNgungThaoLuan(JSONObject params, Address address) throws NumberFormatException,
			JSONException {
		Log.i("Phu","in NhanYeuCauNgungThaoLuan");
		// quyen thao luan =false==4 //tam thoi la quyen chat rieng=7
		if (_peer.getAccount().getRuleById(4) != null) {
			_peer.getAccount().getRuleById(4).setSend(false);
			Iterator<String> listKey = params.keys();
			String key;
			int time = 0;
			while (listKey.hasNext()) {
				Log.d("Phu", "vao while");
				key = listKey.next();
				String s = null;
				try {
					s = params.get(key).toString();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (key.equals("TimeStopTalk")) {
					time = Integer.parseInt(s);
				}

			}
			Log.d("Phu", "moi sua: Send " + _peer.getAccount().getRuleById(7).getSend());
			String s = Protocol.STOP_TALKING_MESSAGE + " trong vòng " + time + " giây. Vui lòng chờ.";
			NetworkController.ShowMessageNoticeTAB(s);
		//	NetworkController.ShowMessageNoticeOnTree(s);
		}
	}

	public static void NhanChoPhepThaoLuan() {
		if (_peer.getAccount().getRuleById(4) != null) {
			_peer.getAccount().getRuleById(4).setSend(true);
			Log.d("Phu", "Da sua lai wuyen noi" + _peer.getAccount().getRuleById(7).getSend());
			NetworkController.ShowMessageNoticeTAB(Protocol.ACCEPT_TALKING_MESSAGE);
			//NetworkController.ShowMessageNoticeOnTree(Protocol.ACCEPT_TALKING_MESSAGE);
		}
	}

	// Quyen 7
	public static void GuiTinNhanChat(Address toAddress, String content) {

		PingMessage mess = new PingMessage(_peer.getPeerDescriptor());
		mess.setType(Protocol.CHAT_MESSAGE);
		Payload pl = new Payload();
		pl.addParam("Content_Chat", content);
		mess.setPayload(pl);
		_peer.send(new Address(toAddress), mess);
		Log.d("Phu", "GuiTinNhanChat to" + toAddress.toString());
	}

	public static void GuiPhanHoiKhongCoQuyenChat(Address toAddress, String username) {
		Log.d("Phu", "gui phan hoi ko co quyen chat");
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.CHAT_FEEDBACK_NON_RULE);
		Payload pl = new Payload();
		pl.addParam("Content", username + " không có quyền nhận tin nhắn trò chuyện.");
		message.setPayload(pl);
		_peer.send(new Address(toAddress), message);
	}

	public static void NhanPhanHoiKhongCoQuyenTroChuyenRieng(JSONObject params, Address address)
			throws NumberFormatException, JSONException {
		String key;

		Iterator<String> listKey = params.keys();
		while (listKey.hasNext()) {
			key = listKey.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (key.equals("Content")) {

				NetworkController.ShowMessageNoticeTAB(s);
			}
		}

	}

	// ========Quyen 5
	// gửi thông báo cần biểu quyết để mời 1 thành viên ra khỏi nhóm
	public static void SendVoteKickMember(Address toAddress, Address beingKick, int time) {
		Log.d("Phu", "vao send vote");
		Log.d("Phu", "being ip = " + beingKick.toString());
		ArrayList<CMember> memberList = ReadXML.ReadMember(ReadWriteFileController.MEMBER_PATH);
		Log.d("Phu", "member size = " + memberList.size());
		String ipPort = "sip:" + beingKick.getURL();
	//	Log.d("Phu", "ip being gan= " + ipPort);
		CMember ipMember = new CMember();
		for (CMember m : memberList) {
			Log.d("Phu", "send ip = " + m.get_ip());
			if (m.get_ip().equals(beingKick.toString())) {
				ipMember = m;
				break;
			}

		}
		if (ipMember != null) {
			Log.d("Phu", "member" + ipMember.get_userName());
			Log.d("Phu", "vao if send vote");
			PingMessage message = new PingMessage(_peer.getPeerDescriptor());
			message.setType(Protocol.KICK_MEMBER_OUT_MESSAGE);
			Payload pl = new Payload();

			pl.addParam("Time", time);
			pl.addParam("IPBeingKick", beingKick.getURL());
			pl.addParam("UserNameBeing", ipMember.get_userName());

			Log.d("Phu", "ip bi kick " + beingKick.getURL());
			message.setPayload(pl);
			_peer.send(toAddress, message);
			Log.d("Phu", "da send vote");
		}
	}
	
	//truyen vao ca username nguoi bi kick
	public static void SendVoteKickMemberGroup(String userName, Address beingKick, int time) {
		Log.d("Phu", "vao SendVoteKickMemberGroup");
		Log.d("Phu", "being ip = " + beingKick.toString());
		ArrayList<CMember> memberList = ReadXML.ReadMember(ReadWriteFileController.MEMBER_PATH);
		Log.d("Phu", "member size = " + memberList.size());
		String ipPort = "sip:" + beingKick.getURL();
		//Log.d("Phu", "ip being gan= " + ipPort);
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.KICK_MEMBER_OUT_MESSAGE);
		Payload pl = new Payload();

		pl.addParam("Time", time);
		pl.addParam("IPBeingKick", beingKick.getURL());
		pl.addParam("UserNameBeing", userName);

		Log.d("Phu", "ip bi kick " + beingKick.getURL());
		message.setPayload(pl);
		CMember ipMember = new CMember();
		for (CMember m : memberList) {
			Log.d("Phu", "send to ip = " + m.get_ip());
			_peer.send(new Address(m.get_ip()), message);
		}
	}

	// gửi ý kiến biểu quyết về việc mời 1 thành viên ra khỏi nhóm
	public static void SendFedbackKickMember(Address toAddress, int vote) {
		Log.d("Phu", "vao ham SendFedbackKickMember");
		// int vote=frmBieuQuyetMoiRoiNhom.YKienBieuQuyet;
		Log.d("Phu", "bieu quyet kick = " + vote);
		// Quyen myRule = _peer.getAccount().getRuleById(13);
		// if (myRule != null && myRule.getSend()) {
		//Log.d("Phu", "vao if bieu quyet kick");
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.KICK_MEMBER_OUT_FEEDBACK);
		Payload pl = new Payload();
		if (vote == 1) {
			Log.d("Phu", " bieu quyet kick = yes");
			pl.addParam("VOTE", "1");
		} else if (vote == 0) {
			Log.d("Phu", " bieu quyet kick = no");
			pl.addParam("VOTE", "0");
		} else {
			Log.d("Phu", " bieu quyet kick = khac");
		}
		message.setPayload(pl);
		_peer.send(toAddress, message);
		// } else {

		// NetworkController.ShowMessageNotice("bạn không có quyền biểu quyết kick");
		// Log.d("Phu", "ko co quyen bieu quyet kick");
		// }
	}

	// hàm gửi kết quả cuoi cung ve moi nguoi khac ra khoi nhom
	public static void SendResultVoteKickMember(Address toAdd, int result, Address beingKickAdd) {
		Log.d("Phu", "vao ham SendResultVoteKickMember");

		Log.d("Phu", "send result to : "+toAdd.getURL());
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.KICK_MEMBER_OUT_RESULT);
		Payload pl = new Payload();

		pl.addParam("Result", result);
		pl.addParam("BeingKick", beingKickAdd.getURL());
		message.setPayload(pl);
		_peer.send(toAdd, message);
		Log.d("Phu", "da send result kick");

	}

	public static void ReceiveVoteKickMember(JSONObject params, Address address) throws NumberFormatException,
			JSONException {
		Log.d("Phu", "Vao ReceiveVoteKickMember");

		
		frmBieuQuyetMoiRoiNhom.senderKick = address;
		// NetworkController.ShowMessageNotice("da nhan dc tin nhan Kick");
		// ActivityController.ShowMessage("nhan dc");
		String key;
		int time = 0;
		String ipBeingKick = "";
		String ip = _peer.getAddressPeer();
		Log.d("Phu", "my ip " + ip);
		Iterator<String> listKey = params.keys();
		String userNameBeingKick = "";
		while (listKey.hasNext()) {
			Log.d("Phu", "vao while");
			key = listKey.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (key.equals("Time")) {
				Log.d("Phu", "key = time");
				Log.d("Phu", "s =" + s);
				time = Integer.parseInt(s);
				Log.d("Phu", "time=" + time);
			}
			if (key.equals("IPBeingKick")) {
				Log.d("Phu", "key = being kick ip");
				ipBeingKick = s;
				Log.d("Phu", "being kick ip=" + ipBeingKick);
			}
			if (key.equals("UserNameBeing")) {
				userNameBeingKick = s;
			}
		}
		Log.d("Phu", "ra khoi while");

		// NetworkController.SetTimeKick(time);

		// có viết hàm thông qua các class controller va activitycontroller
		// nhung ko thanh cong nen gan truc tiep
		Log.d("Phu", "settime kick");
		Log.d("Phu", "time to vote = " + time);
		Quyen myRule = _peer.getAccount().getRuleById(13);
		if (myRule != null && myRule.getSend()) {//co quyen bieu quyet
			if (ip.equals(ipBeingKick) == false) {
				Log.d("Phu", "ko khop ip trong send vote");
				frmBieuQuyetMoiRoiNhom.timeVoteKick = time;
				frmBieuQuyetMoiRoiNhom.beingKickUserName = userNameBeingKick;
				NetworkController.DislayVoteKickMember();
				return;
			}
		}
		Log.d("Phu", "la nguoi bi kick");
//		NetworkController.ShowMessageNotice("Các thành viên trong nhóm đang biểu quyết để mời bạn rời khỏi nhóm.");
		NetworkController.ShowMessageNoticeTAB("Các thành viên trong nhóm đang biểu quyết để mời bạn rời khỏi nhóm.");
		//NetworkController.ShowMessageNoticeOnTree("Các thành viên trong nhóm đang biểu quyết để mời bạn rời khỏi nhóm.");
		// set tat ca cac quyen cua nguoi nay la false.
		// ko cho chat rieng
		NetworkController._peer.getAccount().getRuleById(7).setSend(false);
		// ko cho thao luan
		NetworkController._peer.getAccount().getRuleById(4).setSend(false);
		// ko cho bieu quyet
		NetworkController._peer.getAccount().getRuleById(8).setSend(false);
		// ko cho Chia sẻ tài liệu (Up tài liệu)
		NetworkController._peer.getAccount().getRuleById(9).setSend(false);
		// ko cho Tải tài liệu
		NetworkController._peer.getAccount().getRuleById(10).setSend(false);
		// ko cho xóa tài liệu
		NetworkController._peer.getAccount().getRuleById(11).setSend(false);
		// ko cho Biểu quyết
		NetworkController._peer.getAccount().getRuleById(13).setSend(false);
		// ko cho Đánh giá bản thân và người khác
		NetworkController._peer.getAccount().getRuleById(15).setSend(false);

		// phai phong truong hop no nhan duoc thong bao nay tu nhien roi
		// khoi nhom.ko cho quyet dinh.
		Log.d("Phu", "Da show thong bao ");
	}

	public static void ReceiveFeedbackKickMember(JSONObject params) throws NumberFormatException, JSONException {
		String key;
		Iterator<String> listKey = params.keys();
		while (listKey.hasNext()) {
			key = listKey.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (key.equals("VOTE")) {
				Log.d("Phu", "lay vote="+s);
				if (s.equals("1")) {
					Log.v("Phu","vao add yes");
					//FrmTabActivity.yesVote.add(1);
					frmTreeNodeActivity.yesVote.add(1);
					Log.v("Phu","da add yes");
				} else if (s.equals("0")) {
					Log.v("Phu","vao add yes");
				//	FrmTabActivity.noVote.add(1);
					frmTreeNodeActivity.noVote.add(1);
					Log.v("Phu","da add no");
				}
			}
		}
	}

	public static void ReceiveResultKickMember(JSONObject params) throws NumberFormatException, JSONException {
		String key;
		int kq = -1; 

		Iterator<String> listKey = params.keys();
		String myIP = _peer.getAddressPeer();
		Log.d("Phu", "my IP=" + myIP);
		String ipBeingKick = "";
		while (listKey.hasNext()) {
			key = listKey.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (key.equals("Result")) {
				Log.d("Phu", "lay ket qua cuoi cung");
				if (s.equals("1")) {
					// NetworkController.ShowMessageNotice("Thành viên trên đã bị mời khỏi nhóm");
					kq = 1;
				} else if (s.equals("0")) {
					kq = 0;
					// NetworkController.ShowMessageNotice("Mời thành viên khỏi nhóm đã thất bại.");
				}
				Log.d("Phu", "ket qua cuoi cung = " + s);
			}
			if (key.equals("BeingKick")) {
				Log.d("Phu", "lay ip bi kick result");
				Log.d("Phu", "ip bi kick result : " + s);
				ipBeingKick = s;
				// Log.d("Phu","My ip result : "+myIP.getURL());
			}
		}
		ArrayList<CMember> memberList = ReadXML.ReadMember(ReadWriteFileController.MEMBER_PATH);
		String ipPort = "sip:" + ipBeingKick;
		CMember ipMember = new CMember();
		for (CMember m : memberList) {
			if (m.get_ip().equals(ipPort)) {
				ipMember = m;
				break;
			}

		}
		if (ipBeingKick.equals(myIP)) {
			Log.d("Phu", "khop ip bi kick result");
			if (kq == 1) {
				Log.d("Phu", "kq bi kick result =1 ");
				NetworkController.ShowMessageKicked();
				// xoa nguoi nay khoi danh sach nhom

			} else {
				Log.d("Phu", "kq bi kick result =0 ");
				//NetworkController.ShowMessageNotice("Mời bạn rời khỏi nhóm đã thất bại.");
				NetworkController.ShowMessageNoticeTAB("Mời bạn rời khỏi nhóm đã thất bại.");
			//	NetworkController.ShowMessageNoticeOnTree("Mời bạn rời khỏi nhóm đã thất bại.");
			}
		} else {
			Log.d("Phu", "ko khop ip bi kick result");
			if (kq == 1) {
				Log.d("Phu", "kq bi kick result =1 ");
				String s = "";
				s += ipMember.get_userName() + " đã bị mời ra khỏi nhóm.";
			//	NetworkController.ShowMessageNotice(s);
				NetworkController.ShowMessageNoticeTAB(s);
				//NetworkController.ShowMessageNoticeOnTree(s);
			} else {
				Log.d("Phu", "kq bi kick result =0 ");
				//NetworkController.ShowMessageNotice("Mời thành viên khỏi nhóm đã thất bại.");
				NetworkController.ShowMessageNoticeTAB("Mời thành viên khỏi nhóm đã thất bại.");
				//NetworkController.ShowMessageNoticeOnTree("Mời thành viên khỏi nhóm đã thất bại.");
			}

		}
	}

	public static void ShowMessageKicked() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.ShowMessageKicked();
			}
		});
	}

	public static void CloseDiscussActivity() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.FinishDiscussActivity();
			}
		});
	}

	public static void CloseChatPeerActivity() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				 ActivityController.FinishChatPeerActivity();
			}
		});
	}

	
	// =====end truc==================================================

	public static void init(String name, int port, AccountDTO account) {
		Log.d("Phu", " NetworkController init ");
		_peer = new NetworkLayer(null, "4654amv65d4as4d65a4", name, port, account);
		
	}
	
	//**************
	// ----An
	//**************
	
	// Ham Send Group Sign Out
	public static void sendGroupSignOut(String toAddress, String name) {
		Log.d("PEERDROID", "da nhan duoc name sign out." + name);
		Payload p = new Payload();
		p.addParam("NAME", name);
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.GROUP_SIGN_OUT);
		message.setPayload(p);
		_peer.send(new Address(toAddress), message);
		Log.d("PEERDROID", "send group sign out...");
	
	}

	// Ham Send Group Danh Gia
	public static void sendGroupDanhGia(String toAddress) {
		
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.GROUP_DANH_GIA);
		_peer.send(new Address(toAddress), message);
		Log.d("PEERDROID", "send group danh gia..");
		
	}

	// Ham Send Result Danh Gia
	public static void sendResultDanhGia(String toAddress, String result) {
		
		Payload p = new Payload();
		p.addParam("RESULT", result);
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.RESULT_DANH_GIA);
		message.setPayload(p);
		_peer.send(new Address(toAddress), message);
		Log.d("PEERDROID", "send result danh gia...");
		
	}

	// Ham Send Group Bieu Quyet
	public static void sendGroupBieuQuyet(String toAddress, int index, String title) {
		
		Payload p = new Payload();
		p.addParam("INDEX", index);
		p.addParam("TITLE", title);
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.GROUP_BIEU_QUYET);
		message.setPayload(p);
		_peer.send(new Address(toAddress), message);
		Log.d("PEERDROID", "send group bieu quyet...");
		
	}

	// Ham Send Result Bieu Quyet
	public static void sendResultBieuQuyet(String toAddress, int index, int value) {
		
		Payload p = new Payload();
		p.addParam("INDEX", index);
		p.addParam("VALUE", value);
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.RESULT_BIEU_QUYET);
		message.setPayload(p);
		_peer.send(new Address(toAddress), message);
		Log.d("PEERDROID", "send ket qua bieu quyet...");
	
	}

	// Ham Send Text Log
	public static void sendTextLog(String toAddress, String text, String name) {
		Payload p = new Payload();
		p.addParam("TEXT", text);
		p.addParam("NAME", name);
		PingMessage message = new PingMessage(_peer.getPeerDescriptor());
		message.setType(Protocol.LOG_FILE);
		message.setPayload(p);
		_peer.send(new Address(toAddress), message);
		Log.d("PEERDROID", "send text log...");
	
	}
	
	public static boolean sendAddTextNode(Address toAddress,long parentID, INodeText node) {
		PingMessage msg = new PingMessage(_peer.getPeerDescriptor());
		Payload payload = new Payload();
		payload.addParam("TEXT_NODE", node.toParse());
		payload.addParam("TEXT_NODE_ID", parentID+"");
		msg.setType(Protocol.ADD_TEXT_NODE);
		msg.setPayload(payload);
		_peer.send(toAddress, msg);
		Log.d("Phu", "Da send sendAddTextNode to:" + toAddress.toString()+" parentID="+parentID);
		return true;
	}
	// ***************************
	//
	// ------ Cac Ham Receive ----
	//
	// ***************************

	// Receive Result Danh gia
	public static void ReceiveDanhGia(JSONObject params, final Address sender) {
		Log.d("PEERDROID", "vao ham ReceiveDanhGia");
		
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.ShowDanhGia(sender);
			}
		});
	}
	// Receive Bieu Quyet
	public static void ReceiveBieuQuyet(JSONObject params, final Address sender) {

		Iterator<String> iter = params.keys();
		final int index;
		int i = 0;
		final String title;
		String str = "";
		while (iter.hasNext()) {

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (key.equals("INDEX")) {

				i = Integer.valueOf(s);
			}
			if(key.equals("TITLE")){
				str = s;
			}
		}
		// frmBieuQuyetActivity.timeVote = time;
		title = str;
		index = i;
		Log.d("PEERDROID", "title " + title);
		Log.d("PEERDROID", "index " + index);
		ActivityController.handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Log.d("PEERDROID", "vao handler..........");
				trucActivity.showNotificationBieuQuyet(index, sender,title);
			}
		});
		Log.d("PEERDROID", "vao ham ReceiveBieuQuyet");
	}

	// Receive Result Danh gia
	public static void ReceiveResultDanhGia(JSONObject params, final Address sender) {
		Log.d("PEERDROID", "vao ham ReceiveResultDanhGia");
		Iterator<String> iter = params.keys();
		final String result;
		String str = "";
		while (iter.hasNext()) {

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (key.equals("RESULT")) {
				str = s;
			}
		}
		result = str;
		Log.d("PEERDROID", "Ket qua: " + result);
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.CountResultDanhGia(result);
			}
		});
	}

	// Ham receive Result Bieu Quyet
	public static void ReceiveResultBieuQuyet(JSONObject params, final Address sender) {
		Log.d("PEERDROID", "vao ham ReceiveResultDanhGia");
		Iterator<String> iter = params.keys();
		final int index;
		final int value;
		int in = 0;
		int va = 0;
		while (iter.hasNext()) {

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (key.equals("INDEX")) {
				Log.d("PEERDROID", "index: " + s);
				in = Integer.parseInt(s);
			}
			if (key.equals("VALUE")) {
				Log.d("PEERDROID", "value: " + s);
				va = Integer.parseInt(s);
			}
		}
		index = in;
		value = va;
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.CountResultBieuQuyet(index, value);
			}
		});
	}
	
	// Ham receive Sign Out
	public static void ReceiveSignOut(JSONObject params, final Address sender){
		Log.d("PEERDROID", "vao ham ReceiveSignOut");
		Iterator<String> iter = params.keys();
		final String name;
		String n = "";
		while (iter.hasNext()) {

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}if(key.equals("NAME")){
				n = s;
			}
		}
		name = n;
		Log.d("PEERDROID", "name sign out da nhan: " + name);
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ActivityController.ShowSignOut(name);
			}
		});
	}
	
	// Ham receive Text Log
	public static void ReceiveTextLog(JSONObject params, final Address sender){
		boolean isTrue = _peer.account.isThanhLapNhom; 
		if(isTrue == true){
			Log.d("PEERDROID", "vao ham ReceiveTextLog");
			Iterator<String> iter = params.keys();
			final String Text;
			final String Name;
			String t = "";
			String n = "";
			while (iter.hasNext()) {
	
				String key = iter.next();
				String s = null;
				try {
					s = params.get(key).toString();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}if(key.equals("TEXT")){
					t = s;
				}if(key.equals("NAME")){
					n = s;
				}
			}
			Text = t;
			Name = n;
			Log.d("PEERDROID", "Tex log da nhan: " + Name + Text);
			handler.post(new Runnable() {
	
				@Override
				public void run() {
					// TODO Auto-generated method stub
					ActivityController.WriteTextToLog(Text,Name);
				}
			});
		}
		else{
			Log.d("PEERDROID", "ko co quyen nhan text Log" );
		}
	}
	//***********************
	//---end An
	//**********************
	/**
	 * Đặt lại vai trò cho account<br>
	 * 1.Reset role<br>
	 * 2.Đọc role từ file lên
	 */
	public static boolean resetRole() {
		Log.d("Phu", "NetworkController reset Role");
		_peer.account.resetRole();
		ArrayList<RoleDTO> roleList = ReadWriteFileController.readRole(null,ReadWriteFileController.MY_ROLE_PATH);
		for (RoleDTO role : roleList) {
			_peer.account.addRole(role);
			Log.d("Phu", "Role name: " + role.getName());
		}
		if(roleList.size()==0)
			return false;
		return true;
	}

	public static boolean getIsThanhLapNhom() {
		return _peer.account.isThanhLapNhom;
	}

	/**
	 * Lấy 2(3) số cuối của địa chỉ IP Phục vụ cho việc định danh node trong cây
	 * thảo luận
	 * 
	 * @return
	 */
	public static long getPersonID() {
		nodeCurrenIndex++;
		String s = _peer.getSimpleIP();
		String[] m = s.split("\\.");
		return Integer.parseInt(m[3]) * 1000 + System.currentTimeMillis();
	}
	public static synchronized boolean getStated(){
		return isConnected;
	}
	public static synchronized void setStated(boolean conneted){
		isConnected=conneted;
	}

	
	//=============END TRUC========================================
	
	
	/*----------Các hàm Đăng nhập, tìm kiếm user trong mạng, Đăng xuất------------*/
	public static Thread searchThread(String nameThread)
	{
		Thread temp = new Thread("default");
		for(Thread t: ARRAY_THREAD)
			if(t.getName().equals(nameThread))
				return t;
		return temp;
	}
	public static void removeThread(Thread t)
	{
		t.interrupt();
		ARRAY_THREAD.remove(t);
	}
	public static void Login(Address address,String userName, String pass)
	{
		_peer.SendAccountLearnerToTeacher(address, userName, pass);
	}

	public static void isLogin(JSONObject params) throws NumberFormatException, JSONException
	{
		_isLogin = 0;
		Iterator<String> iter = params.keys();
		while(iter.hasNext()){			
			String key = iter.next();
			if(key.equals("info"))
			{
				if(params.get(key).toString().equals("Error"))
				{
					_isLogin=1;
					//FrmLogin.get_dialog().dismiss();

				}
				else
				{
					String s = null;
					_isLogin=2;

					try {
						s = params.get(key).toString();
						//ReadWriteFileController.WriteDetailLeanrer(s);
						ReadWriteFileController.WriteDetailLeanrerToDB(s);
						sendInfoReDangnhap(new Address(_ipHost), _idLearner);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}
		}

		/*Document doc = null;
		String fname = Environment.getExternalStorageDirectory().toString()+"/ttgv.xml";
		doc = WriteXML.WriteXMLLearner(doc, fname);
		doc = WriteXML.insertTagRoot(doc,fname,"ThongTinGiaoVien",ip+":"+port);*/	

	}
	public static void sendInfoReDangnhap(Address addr, int idlearner)
	{
		Payload p = new Payload();
		p.addParam("idlearner",idlearner);
		_peer.sendInfoReDangnhap(addr,p);
	}
 
	public static void SendMessageLogout()
	{
		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ArrayList<String> ipList = ReadXML.ReadIP(ReadWriteFileController.pathNeighborsList);
				for(String ip:ipList)
					_peer.SendMessageLogout(new Address(ip));
				NetworkController.peerRelease();
				Log.d("PEERDROID","tat peer");
				ReadWriteFileController.deleteFile(ReadWriteFileController.pathNeighborsList);
				//xoá tất cả nội dung tin nhắn group:
				ReadWriteFileController.deleteFolder(ReadWriteFileController.DIRECTORYCHATGROUP);
				Log.d("PEERDROID","Đã Thoát khỏi chương trình");
				System.exit(0);
				Thread.currentThread().interrupt();

			}
		});
		t.start();
	}

	public static void ReceiveUserList(JSONObject params)throws NumberFormatException, JSONException
	{
		String s=null;
		Iterator<String> iter = params.keys();
		while(iter.hasNext()){			
			String key = iter.next();
			if(key.equals("userlist"))
			{
				try {
					s = params.getString(key);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}



				//tạo file NeighborsList lưu danh sách các hàng xóm trong lớp
				String path = ReadWriteFileController.pathNeighborsList;
				Document doc = null;
				WriteXML.insertRoot(doc, path, "ListLearner");
				_isWriteNeighborsList = true;

				//thực hiện gửi thông điệp hello đến các ip trong user list
				SendHelloToListUser(s);
			}
		}
	}

	public static void SendHelloToUser(Address addr)
	{
		_peer.SendHelloToUser(addr);
	}

	public static void SendHelloToListUser(String str)
	{
		String[] ipList = str.split("/");
		if(ipList[0].equals(""))
			return;
		int n = ipList.length;
		for(int i = 0; i < n; i++)
		{
			//kiểm tra ip mình thì ko send
			if(!ipList[i].equals(_ipUser))
			{
				Address addr = new Address(ipList[i]);
				SendHelloToUser(addr);
			}
			
		}
	}
	public static void ReceiveHello(JSONObject params, Address address)throws NumberFormatException, JSONException
	{
		Iterator<String> iter = params.keys();
		final CMember cmem = new CMember();
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("fullname"))
			{
				cmem.set_fullName(s);
			}
			else if(key.equals("username"))
			{
				cmem.set_userName(s);
			}
		}
		final Address addr = address;
		Log.d("PEERDROID","count thread trc: " + Thread.activeCount());
		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				cmem.set_ip(addr.getHost()+":"+addr.getPort());
				String path = ReadWriteFileController.pathNeighborsList;
				//kiểm tra ip đã tồn tại
				Document doc = ReadXML.BuildXML(path);
				if(ReadWriteFileController.isExistUserName(path, cmem.get_userName()))
				{
					doc = WriteXML.deleteTagElement(doc, path, "Learner", "UserName", cmem.get_userName());
				}
				WriteXML.insertMember(doc, path, cmem);
				//tồn tại rồi thì update thêm thông tin
				//chưa tồn tại thì lưu xuống file


				//thực hiện gửi rehello
				_peer.SendReHelloToUser(new Address(cmem.get_ip()));

				//lưu thông tin xuống csdl

				//show member lên danh sách user
				ActivityController.handler.post(get_runUpdateUserList());
				Thread.currentThread().interrupt();
			}
		});
		t.setName("Hello");
		t.start();
		Log.d("PEERDROID","count thread sau: " + Thread.activeCount());
	}

	public static void ReceiveReHello(JSONObject params, Address address)throws NumberFormatException, JSONException
	{
		//lưu thông tin user xuống csdl
		Iterator<String> iter = params.keys();
		final CMember cmem = new CMember();
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("fullname"))
			{
				cmem.set_fullName(s);
			}
			else if(key.equals("username"))
			{
				cmem.set_userName(s);
			}
		}
		final Address addr = address;
		Log.d("PEERDROID","count thread trc: " + Thread.activeCount());
		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				cmem.set_ip(addr.getHost()+":"+addr.getPort());
				//lưu neighbor vào ds
				String path = ReadWriteFileController.pathNeighborsList;
				Log.d("PEERDROID","pathNeighborsList: " + path);
				//kiểm tra ip đã tồn tại
				Document doc = ReadXML.BuildXML(path);
				if(ReadWriteFileController.isExistUserName(path, cmem.get_userName()))
				{
					doc = WriteXML.deleteTagElement(doc, path, "Learner", "UserName", cmem.get_userName());
				}
				WriteXML.insertMember(doc, path, cmem);

				//show member lên danh sách user
				ActivityController.handler.post(get_runUpdateUserList());
				Thread.currentThread().interrupt();
			}
		});
		t.setName("reHello");
		t.start();
		Log.d("PEERDROID","count sau thread: " + Thread.activeCount());
	}

	public static void ReceiveInfoTeacher(JSONObject params, Address address)
	{

		//lưu thông tin user xuống csdl
		Log.d("PEERDROID","vao ham nhan ReceiveInfoTeacher");
		Iterator<String> iter = params.keys();
		final CMember cmem = new CMember();
		int idteacher = 0;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("id"))
			{
				idteacher = Integer.valueOf(s);
			}
			if(key.equals("fullname"))
			{
				cmem.set_fullName(s);
			}
			else if(key.equals("username"))
			{
				cmem.set_userName(s);
			}
		}
		final int id = idteacher;
		final Address addr = address;
		Log.d("PEERDROID","_isWriteNeighborsList" + _isWriteNeighborsList);
		Log.d("PEERDROID","count thread trc: " + Thread.activeCount());
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Log.d("PEERDROID","sender: " + addr);

				while(_isWriteNeighborsList == false)
				{
					Log.d("PEERDROID","_isWriteNeighborsList" + _isWriteNeighborsList);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				//				sau khi đã ghi được file NeighborsList, thực hiện ghi thông tin giáo viên:
				//				cập nhật vào csdl:
				TeacherDAO tDao = new TeacherDAO(null);
				
//				int idTeacher = tDao.getIDTeacher(cmem.get_userName());
				Log.d("PEERDROID","luu teacher vao csdl: idTeacher:" + id);
				if(!tDao.isExist(id))
//				{
//					Log.d("PEERDROID","update teacher " );
//					TeacherDTO tDto = new TeacherDTO(cmem.get_fullName(), cmem.get_userName(), idTeacher);
//					tDao.updateTeacher(tDto);
//				}
//				else
				{
					Log.d("PEERDROID","insert teacher " );
					TeacherDTO tDto = new TeacherDTO(cmem.get_fullName(), cmem.get_userName(), id);
					tDao.insertTeacher(tDto);
				}	
				Log.d("PEERDROID","sender: " + addr);
				_userNameTeacher = cmem.get_userName();
				cmem.set_ip(addr.getHost()+":"+addr.getPort());
				//lưu neighbor vào ds
				String path = ReadWriteFileController.pathNeighborsList;
				Document doc = ReadXML.BuildXML(path);
				//kiểm tra ip đã tồn tại

				if(ReadWriteFileController.isExistUserName(path, cmem.get_userName()))
				{
					Log.d("PEERDROID","vao delete");
					doc = WriteXML.deleteTagElement(doc, path, "Learner", "UserName", cmem.get_userName());
				}
				WriteXML.insertMember(doc, path, cmem);

				//show member lên danh sách user
				ActivityController.handler.post(get_runUpdateUserList());

				//dong bo du lieu
				NetworkController.SendIDMax(new Address(_ipHost));
				Thread.currentThread().interrupt();
				Log.d("PEERDROID","count thread sau: " + Thread.activeCount());
			}
		});
		t.start();

	}
	public static void ReceiveUserLogout(JSONObject params, Address addr)
	{
		//lưu thông tin user xuống csdl
		Log.d("PEERDROID","vao ham nhan ReceiveUserLogout");
		Iterator<String> iter = params.keys();
		String ipUserLogOut = "";
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("Logout"))
			{
				ipUserLogOut = s;
			}
		}
		String path = ReadWriteFileController.pathNeighborsList;
		WriteXML.deleteIP(path, ipUserLogOut);
		ActivityController.handler.post(get_runUpdateUserList());
	}

	/*-------------------Các nhận, gửi bài tập; thông tin feedback----------------*/
	public static void SendFeedbackToTeacher(Address addr, int idFeelChoice, int idDetailLearning, int idFeelType, int idLearner)
	{
		Payload p = new Payload();
		//		p.addParam("idlearner", idLearner);
		p.addParam("idfeeltype", idFeelType);
		p.addParam("reactivefeedback", idFeelChoice);
		p.addParam("iddetaillearning", idDetailLearning);
		p.addParam("idlearner", idLearner);
		_peer.SendFeedbackToTeacher(addr, p);
	}
	public static void SendAllFeedbackToTeacher(Address addr, int idChapter, int idLearner, String choice)
	{
		Payload p = new Payload();
		p.addParam("choice", choice);
		p.addParam("idchapter", idChapter);
		//		p.addParam("idclass", idClass);
		p.addParam("idlearner", idLearner);
		_peer.SendAllFeedbackToTeacher(addr, p);
	}

	public static void SendResultToTeacher(Address add, String fName)
	{
		Payload p = ReadWriteFileController.ReadFeeback(fName);
		_peer.SendResultToTeacher(add, p);
	}

	public static void ReceiveResultTest(JSONObject params)
	{
		Iterator<String> iter = params.keys();
		ArrayList<ArrayList<Object>> resList = new ArrayList<ArrayList<Object>>();
		int idDetailLearning = 0;
		int idPart = 0;
		int idExercises = 0;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("iddetaillearning"))
			{
				idDetailLearning = Integer.valueOf(s);
				DetailLearningDAO dlDao = new DetailLearningDAO(null);
				idPart =dlDao.getIDPart(idDetailLearning); 
			}
			if(key.equals("idexercises"))
			{
				idExercises = Integer.valueOf(s);
			}
			String[] sArr = s.split(getSeparator());
			if(sArr.length>2)
			{	
				ArrayList<Object> res = new ArrayList<Object>();

				//idquestion
				res.add(sArr[0]);
				int n = sArr.length;

				//type
				res.add(sArr[n-1]);

				//đáp án
				for(int i = 1; i < n - 1; i++)
					res.add(sArr[i]);
				resList.add(res);
			}


		}
		String path = idPart + "_"+ idExercises +"_"+ "FullTest_" + idDetailLearning;
		WriteXML.insertResultTest(path, resList);
		ReadWriteFileController.updateStatusUsingQuestionList(path, 3);
		FrmShowResultOfTest.set_fNameQues(path);
		FrmShowResultOfTest.set_status(3);
		NotificationController.sendNotification(ActivityController.getPeerActivity().getBaseContext(), FrmShowResultOfTest.class, "Thông báo", "Xem đáp án", Notification.DEFAULT_SOUND);
	}

	public static void ReceiveFeelType(JSONObject params)
	{
		Iterator<String> iter = params.keys();
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("feeltype"))
			{
				ArrayList<ArrayList<String>> feedbackList = FeelTypeDTO.getFeedBackList(s);
				for(ArrayList<String> feedback : feedbackList)
				{
					FeelTypeDTO ftDto = new FeelTypeDTO();
					ftDto.set_ID(Integer.valueOf(feedback.get(0)));
					ftDto.set_Name(feedback.get(1));

					FeelTypeDAO ftDao = new FeelTypeDAO(null);

					//chua tồn tại thì insert vào csdl
					if(!ftDao.isExist(ftDto.get_ID()))
						ftDao.insert(ftDto);

					int n = feedback.size();
					for(int i = 2; i < n; i+=2)
					{
						FeelChoiceDTO fcDto = new FeelChoiceDTO();
						fcDto.set_ID(Integer.valueOf(feedback.get(i)));
						fcDto.set_Name(feedback.get(i + 1));
						FeelChoiceDAO fcDao = new FeelChoiceDAO(null);
						//chưa tồn tại thì insert vào csdl
						if(!fcDao.isExist(fcDto.get_ID()))
						{
							fcDao.insert(fcDto);
						}
						UsingFeelListDAO uflDao = new UsingFeelListDAO(null);
						if(!uflDao.isExist(ftDto.get_ID(), fcDto.get_ID()));
						{
							uflDao.insert(ftDto.get_ID(), fcDto.get_ID());
						}
					}
				}
			}
		}
	}

	public static void ReceiveFeedbackFeelType(JSONObject params)
	{
		Iterator<String> iter = params.keys();
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("detaillearning"))
			{
				ArrayList<ArrayList<String>> detailLearningFeelList = DetailLearningDTO.getDetailLearningFeelList(s);
				for(ArrayList<String> detailLearningFeel : detailLearningFeelList)
				{
					//id/idpart/idclass/datelearning/feeltype
					DetailLearningDAO dlDao = new DetailLearningDAO(null);
					DetailLearningDTO dlDto = new DetailLearningDTO();

					dlDto.set_ID(Integer.valueOf(detailLearningFeel.get(0)));
					dlDto.set_IDClass(Integer.valueOf(detailLearningFeel.get(2)));
					dlDto.set_IDPart(Integer.valueOf(detailLearningFeel.get(1)));
					dlDto.set_IDFeelType(Integer.valueOf(detailLearningFeel.get(4)));
					String [] temp = detailLearningFeel.get(3).split(" ");
					dlDto.set_DateLearning(Date.valueOf(temp[0]));
					dlDto.set_Status(false);//trạng thái của feeltype - active hay non active
					///kiểm tra idDetailLearning tồn tại chưa?
					//tồn tại: update lại detailLearning
					//chưa tồn tại: insert mới
					if(dlDao.isExist(dlDto.get_ID()))
					{
						dlDao.updateFeelType(dlDto.get_ID(), dlDto.get_IDFeelType());
					}
					else
					{
						dlDao.insertDetailLearning(dlDto);
					}
				}
			}
		}
	}
	public static void ReceiveActiveFeedback(JSONObject params)
	{
		Iterator<String> iter = params.keys();
		int time=0;
		int idPart = 0;
		int idDetailLearning = 0;
		int idFeelType = 0;
		String feelchoie = null;
		String title = null;
		DetailLearningDAO dlDao = new DetailLearningDAO(null);
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("time"))
			{
				time = Integer.valueOf(s);
				//put wa activity feedbacklist
			}
			else if(key.equals("iddetaillearning"))
			{
				idDetailLearning = Integer.valueOf(s);
				idPart = dlDao.getIDPart(idDetailLearning);
			}
			else if(key.equals("idfeeltype"))
			{
				idFeelType = Integer.valueOf(s);
			}
			else if(key.equals("title"))
			{
				title = s;
			}
			else if(key.equals("feelchoice"))
			{
				feelchoie = s;
			}
			//			if(key.equals("activefeedback"))
			//			{
			//				DetailLearningDAO dlDao = new DetailLearningDAO(null);
			//				int idDetailLearning = Integer.valueOf(s);
			//				idPart = dlDao.getIDPart(idDetailLearning);
			//				if(dlDao.isExist(idDetailLearning))
			//				{
			//					//					int idPart = dlDao.getIDPart(idDetailLearning);
			//					//					int idFeelType = dlDao.getIDFeelType(idDetailLearning);
			//					dlDao.updateStatus(idDetailLearning, true);
			//				}
			//				//active feeback cho part cụ thể
			//				ActivityController.handler.post(new Runnable() {
			//
			//					@Override
			//					public void run() {
			//						// TODO Auto-generated method stub
			//						//	FrmPart.updateListAdapter();
			//					}
			//				});
			//				FrmDoFeedback.set_idPart(idPart);
			//				FrmDoFeedback.set_time_min(time);
			//				NotificationController.sendNotification(ActivityController.getPeerActivity().getBaseContext(), FrmDoFeedback.class, "Thông báo", "Có feeback", Notification.DEFAULT_SOUND);
			//			}
		}
		if(dlDao.isExist(idDetailLearning))
		{
			//cập nhật lại trạng thái active feedback
			dlDao.updateStatus(idDetailLearning, true);
		}
		//active feeback cho part cụ thể
		ActivityController.handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				//	FrmPart.updateListAdapter();
			}
		});
		FrmDoFeedback.set_type(1);
		FrmDoFeedback.set_idPart(idPart);
		FrmDoFeedback.set_time(time);
		FrmDoFeedback.set_idDetailLearning(idDetailLearning);
		FrmDoFeedback.set_idFeelType(idFeelType);
		FrmDoFeedback.set_title("ABC");
		FrmDoFeedback.set_feelchoice(feelchoie);
		NotificationController.sendNotification(ActivityController.getPeerActivity().getBaseContext(), FrmDoFeedback.class, "Thông báo", "Có yêu cầu phản hồi", Notification.DEFAULT_SOUND);

	}

	public static void ReceiveActiveAllFeedback(JSONObject params)
	{
		Iterator<String> iter = params.keys();
		int idClass = 0;
		int idChap = 0;
		int time = 0;
		String feel = null;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("time"))
			{
				time = Integer.valueOf(s);
			}
			if(key.equals("idclass"))
			{
				idClass = Integer.valueOf(s);
			}
			if(key.equals("idchapter"))
			{
				idChap = Integer.valueOf(s);
			}
			if(key.equals("feel"))
			{
				feel = s;
			}
		}
		if(feel.equals(""))
			return;
		PartDAO pDao = new PartDAO(null);
		ArrayList<Integer> idPartList = pDao.getIDPartList(idChap);
		//active feedback toàn bộ part liên quan


		FrmDoFeedback.set_idClass(idClass);
		FrmDoFeedback.set_feel(feel);
		FrmDoFeedback.set_time(time);
		FrmDoFeedback.set_type(2);
		FrmDoFeedback.set_idChap(idChap);
		NotificationController.sendNotification(ActivityController.getPeerActivity().getBaseContext(), FrmDoFeedback.class, "Thông báo", "Có yêu cầu phản hồi", Notification.DEFAULT_SOUND);
	}
	/*-------------Các hàm nhận, gửi thông tin chat, invite group, ...------------*/
	public static void ReceiveInvite(JSONObject params, Address addr)throws NumberFormatException, JSONException
	{
		//lưu thông tin user xuống csdl
		Iterator<String> iter = params.keys();
		String fullName = null;
		String userName = null;
		String info= null;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("fullname"))
			{
				fullName = s;
			}
			else if(key.equals("username"))
			{
				userName = s;
			}
			else if(key.equals("info"))
			{
				info = s;
			}
		}

		//thông báo lên giao diện 
		ActivityController.ShowDialogReceiveInvite(addr, fullName, userName, info);


		//-----------update lai giao dien conversation--------------
	}
	public static void ReceiveReInvite(JSONObject params, Address addr)throws NumberFormatException, JSONException
	{
		Document doc = null;
		CMember mem=new CMember();
		String keychat = null;
		mem.set_ip(addr.getHost()+":"+addr.getPort());
		//lưu thông tin user xuống csdl
		Iterator<String> iter = params.keys();
		int accept = 0;
		while(iter.hasNext()){
			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("accept"))
			{
				accept = Integer.valueOf(s);
			}
			if(key.equals("username"))
			{
				mem.set_userName(s);
			}
			if(key.equals("fullname"))
			{
				mem.set_fullName(s);
			}
			if(key.equals("keychat"))
			{
				keychat = s;
			}
		}
		//		String myUserName=NetworkController.get_userName();
		//		String fName = ReadWriteFileController.DIRECTORY + "Group_"	+myUserName+ "_ipList.xml";
		//thông báo lên giao diện
		if(accept == 1)
		{
			//thuc hien ghi vao nhom
			String myUserName=NetworkController.get_userName();
			String fName = ReadWriteFileController.DIRECTORYCHATGROUP + "Group_"	+myUserName+ "_ipList.xml";

			//			if(ReadWriteFileController.isFile(fName))
			//				doc = WriteXML.insertRoot(doc, fName, "ListLearner");
			doc = ReadXML.BuildXML(fName);
			//--------thong bao cho cac user trong nhom co thanh vien moi----------
			ArrayList<CMember> memlist = ReadXML.ReadMember(doc);
			int n = memlist.size();
			String ipList = "";
			for(int i = 0; i < n; i++)
			{
				ipList += memlist.get(i).get_userName()+ "/" + memlist.get(i).get_fullName()+"/" + memlist.get(i).get_ip() + "##";
				SendInviteUpdateGroup(new Address(memlist.get(i).get_ip()), mem);
			}

			ipList = ipList.substring(0, ipList.length() - 2);

			//--------gui cho thanh vien moi danh sach user hien tai trong nhom-------------
			SendInviteGroup(addr, ipList);

			if(ReadWriteFileController.isExistUserName(fName, mem.get_userName()))
				doc = WriteXML.deleteTagElement(doc, fName, "Learner", "UserName",  mem.get_userName());
			doc = WriteXML.insertMember(doc, fName, mem);

			final ArrayList<Object> message = new ArrayList<Object>();
			message.add(myUserName);
			message.add("");
			message.add(2);
			message.add(mem.get_ip());
			message.add(mem.get_fullName());
			//--------update lai giao dien----------
			ActivityController.handler.post(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					FrmChatInvite.updateListUser();	
					FrmConversation.receiveMessage(message);
				}
			});
			//----------update lai form conversation----------------

		}
		else{
			//			if(ReadWriteFileController.isExistUserName(fName, mem.get_userName()))
			//				doc = WriteXML.deleteTagElement(doc, fName, "Learner", "UserName",  mem.get_userName());
			ActivityController.ShowDialogReceiveReInvite(mem.get_fullName());
		}
	}
	public static void ReceiveInviteLogout(JSONObject params, Address addr)throws NumberFormatException, JSONException, IOException
	{
		//lưu thông tin user xuống csdl
		Iterator<String> iter = params.keys();
		String fullName = null;
		String userName = null;
		String userNameCreater = null;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("fullname"))
			{
				fullName = s;
			}
			else if(key.equals("username"))
			{
				userName = s;
			}
			else if(key.equals("keychat"))
			{
				userNameCreater = s;
			}
		}
		//xóa thông tin user ở file
		String path = ReadWriteFileController.DIRECTORYCHATGROUP + "Group_"	+userNameCreater+ "_ipList.xml";
		String pathContent = ReadWriteFileController.DIRECTORYCHATGROUP + "Group_" + userNameCreater+ "_Content.txt";
		ReadWriteFileController.writeTXTPath(pathContent, fullName + "đã rời khỏi nhóm.");
		Document doc = ReadXML.BuildXML(path);
		ArrayList<Object> attribute = new ArrayList<Object>();
		attribute.add("UserName");
		ArrayList<Object> value = new ArrayList<Object>();
		value.add(userName);
		WriteXML.deleteTagElement(doc, path, "Learner", attribute, value);

		//thông báo lên giao diện - cập nhật lại ds list
		ActivityController.handler.post(_runUpdateMsgInvite);
		//cập nhật lại ds user trong userlist chat group
		ActivityController.handler.post(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				FrmChatInvite.updateListUser();	

			}
		});

	}

	public static void ReceiveSignoutGroup(JSONObject params, Address addr)throws NumberFormatException, JSONException, IOException
	{
		//lưu thông tin user xuống csdl
		Iterator<String> iter = params.keys();
		String fullName = null;
		String userName = null;
		String userNameCreater = null;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("fullname"))
			{
				fullName = s;
			}
			else if(key.equals("username"))
			{
				userName = s;
			}
			else if(key.equals("keychat"))
			{
				userNameCreater = s;
			}
		}
		//xóa thông tin user ở file
		String path = ReadWriteFileController.DIRECTORYCHATGROUP + "Group_"	+userNameCreater+ "_grouping_ipList.xml";
		String pathContent = ReadWriteFileController.DIRECTORYCHATGROUP + "Group_" + userNameCreater+ "_grouping_Content.txt";
		ReadWriteFileController.writeTXTPath(pathContent, fullName + "đã rời khỏi nhóm.");
		Document doc = ReadXML.BuildXML(path);
		ArrayList<Object> attribute = new ArrayList<Object>();
		attribute.add("UserName");
		ArrayList<Object> value = new ArrayList<Object>();
		value.add(userName);
		WriteXML.deleteTagElement(doc, path, "Learner", attribute, value);

		//thông báo lên giao diện - cập nhật lại ds list
		//cập nhật lại ds user trong userlist chat group
		ActivityController.handler.post(_runUpdateMsgGroup);
		ActivityController.updateListUser();

	}

	public static void ReceiveInviteGroup(JSONObject params, Address addr)throws NumberFormatException, JSONException
	{
		//lưu thông tin user xuống csdl
		Iterator<String> iter = params.keys();
		String groupList = null;
		String userNameCreater = null;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("grouplist"))
			{
				groupList = s;
			}
			if(key.equals("keychat"))
			{
				userNameCreater = s;
			}
		}
		//thông báo lên giao diện
		if(groupList != null)
		{
			//lưu xml
			String path = ReadWriteFileController.DIRECTORYCHATGROUP + "Group_"+userNameCreater+ "_ipList.xml";
			Document doc = null;
			if(!ReadWriteFileController.isFile(path))
				doc = WriteXML.insertRoot(doc, path, "ListLearner");
			doc = ReadXML.BuildXML(path);
			String[] arrListMem = groupList.split(getSeparator1());
			for(String strmem : arrListMem)
			{
				String[] arrMem = strmem.split(getSeparator());
				String fullName = arrMem[1];
				String userName = arrMem[0];
				String ip = arrMem[2];
				CMember mem = new CMember(ip, fullName, userName);
				if(ReadWriteFileController.isExistUserName(path, mem.get_userName()))
				{
					doc = WriteXML.deleteTagElement(doc, path, "Learner", "UserName",  mem.get_userName());
				}
				doc = WriteXML.insertMember(doc, path, mem);
			}

			//cập nhật lại ds user trong userlist chat group
			ActivityController.handler.post(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					FrmChatInvite.updateListUser();	
				}
			});
		}
	}
 
	public static void ReceiveInviteUpdateGroup(JSONObject params, Address addr)throws NumberFormatException, JSONException
	{
		//lưu thông tin user xuống csdl
		Iterator<String> iter = params.keys();
		String fullName = null;
		String userName = null;
		String ip = null;
		String userNameCreater = null;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("fullname"))
			{
				fullName = s;
			}
			else if(key.equals("username"))
			{
				userName = s;
			}
			else if(key.equals("ip"))
			{
				ip = s;
			}
			else if(key.equals("keychat"))
			{
				userNameCreater = s;
			}
		}
		//thông báo lên giao diện
		//lưu xml
		String path = ReadWriteFileController.DIRECTORYCHATGROUP + "Group_"+userNameCreater+ "_ipList.xml";
		Document doc = null;
		if(!ReadWriteFileController.isFile(path))
			doc = WriteXML.insertRoot(doc, path, "ListLearner");
		doc = ReadXML.BuildXML(path);
		CMember mem = new CMember(ip, fullName, userName);
		if(ReadWriteFileController.isExistUserName(path, mem.get_userName()))
			doc = WriteXML.deleteTagElement(doc, path, "Learner", "UserName",  mem.get_userName());
		doc = WriteXML.insertMember(doc, path, mem);

		ActivityController.handler.post(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				FrmChatInvite.updateListUser();	
			}
		});
	}
	
	public static void init_runnableUpdateMsg() {
		// install runnable
		_runUpdateMsg = new Runnable() {
			@Override
			public void run() {
				Log.d("PEERDROID","run update message");
			//	FrmChatPeer.updateMessage();
				frmChatPeerActivity.updateMessage();
			}
		};
	}

	public static void init_runnableUpdateUserList() {
		// install runnable

		set_runUpdateUserList(new Runnable() {
			@Override
			public void run() {
				Log.d("PEERDROID","init_runnableUpdateUserList");
				FrmInviteGroupChat.setAdapter();
			}
		});
	}

	public static void init_runnableUpdateMsgGroup() {
		// install runnable
		_runUpdateMsgGroup = new Runnable() {
			@Override
			public void run() {
				FrmChatGroup.updateMessage();
			}
		};
	}

	public static void init_runnableUpdateMsgInvite() {
		// install runnable
		_runUpdateMsgInvite = new Runnable() {
			@Override
			public void run() {
				FrmChatInvite.updateMessage();
			}
		};
	}

	public static void init_runnableUpdateChapter() {
		// install runnable
		_runUpdateChapter = new Runnable() {
			@Override
			public void run() {
				FrmChapter.updateListAdapter();
			}
		};
	}

	public static void init_runnableUpdatePart() {
		// install runnable
		_runUpdateChapter = new Runnable() {
			@Override
			public void run() {
				FrmPart.updateListAdapter();
			}
		};
	}

	public static void ReceiveGrouping(JSONObject params) throws IOException
	{
		String usernamevip = "";
		String temp = null;
		String[] sArr = null;
		Iterator<String> iter = params.keys();
		Document doc = null;
		// doc = WriteXML.WriteXMLReceive(doc, fName, 1, "CSDL", 123);
		while (iter.hasNext()) {
			String key = (String) iter.next();
			String s = null;
			if (key.equals("keychat")) {
				try {
					usernamevip = params.get(key).toString();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (key.equals("ds")) {
				try {
					s = params.get(key).toString();
					temp = s;
					sArr = s.split(SEPARATOR1);
					// CQuestion ques = getQuestion(sArr);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
		String fName = ReadWriteFileController.DIRECTORYCHATGROUP + "Group_" + usernamevip + "_grouping_ipList.xml";
		doc = WriteXML.insertRoot(doc, fName, "ListLearner");
		for (int i = 0; i < sArr.length; i++) {
			CMember mem = ReadWriteFileController.getMember(sArr[i]);
			doc = WriteXML.insertMember(doc, fName, mem);
		}
		ReadWriteFileController.writeTXT(ReadWriteFileController.get_fNameListGroup(), "Group_" + usernamevip + "_grouping_Content");

		final ArrayList<Object> message = new ArrayList<Object>();
		message.add(usernamevip);
		message.add("");
		message.add(3);
		message.add("");
		message.add("Nhóm grouping");

		//--------update lai giao dien----------
		ActivityController.handler.post(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				//				FrmChatGroup.updateListUser();	
				FrmConversation.receiveMessage(message);
			}
		});
		//		ActivityController.updateListUser();
	}
	public static void ReceiveMessageChatGroup(JSONObject params)
	throws IOException {
		Iterator<String> iter = params.keys();
		String usernamevip = "";
		String[] sTemp=null;
		String type=null;
		int typegroup = 0;
		while (iter.hasNext()) {
			String key = iter.next();
			if (key.equals("keychat")) {
				try {
					// -----------su dung key nay de biet dang chat voi group
					// nao?-----------
					usernamevip = params.get(key).toString();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			//loại chat: invite-chatinvite; group-chatgroup
			if (key.equals("type")) {
				try {
					// -----------su dung key nay de biet dang chat voi group
					// nao?-----------
					type = params.get(key).toString();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (key.equals("Message")) {
				String s = null;
				try {
					s = params.get(key).toString();
					sTemp = s.split(getSeparator());

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		String acc = sTemp[0];
		String mess = getMessageGroup(sTemp);
		if(type.equals("invite"))
		{
			typegroup = 2;
			ReadWriteFileController.writeTXTPath(ReadWriteFileController.DIRECTORYCHATGROUP + "Group_" + usernamevip + "_Content.txt", acc + ": "+ mess);
			ActivityController.handler.post(_runUpdateMsgInvite);
		}
		else if(type.equals("group"))
		{
			typegroup = 3;
			ReadWriteFileController.writeTXTPath(ReadWriteFileController.DIRECTORYCHATGROUP + "Group_" + usernamevip + "_grouping_Content.txt", acc + ": "+ mess);
			ActivityController.handler.post(_runUpdateMsgGroup);
		}
		//FrmChatGroup.set_usernameCreater(usernamevip);
		final String ip = null;
		final ArrayList<Object> message = new ArrayList<Object>();
		message.add(usernamevip);
		message.add(mess);
		message.add(typegroup);
		message.add(ip);
		message.add("");
		//		ActivityController.handler.post(_runUpdateMsgGroup);
		// FrmChatPeer.updateMessage();
		ActivityController.handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				FrmConversation.receiveMessage(message);
			}
		});
	}

	public static void UpdateMessageInConversation(String keychat, String mess, int type, String ip, String fullName)
	{
		final ArrayList<Object> message = new ArrayList<Object>();
		message.add(keychat);
		message.add(mess);
		message.add(type);
		message.add(ip);
		message.add(fullName);
		ActivityController.handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				FrmConversation.receiveMessage(message);
			}
		});
	}
	public static void SendChatMessagePeer(Address addr, String message){
		_peer.SendChatPeerMessage(addr, message);
	}

	/**
	 * ham gui thong diep chat nhom
	 */
	public static void SendChatMessageGroup(Address addr, String message,String usernamevip, String type){
		if(!_ipUser.equals(addr.getHost()+":"+addr.getPort()))
			_peer.SendChatMessage(addr, message,usernamevip, type);
	}

	public static void SendInvite(Address addr, String title)
	{
		_peer.SendInvite(addr, title);
	}
	/**
	 * 
	 * @param addr
	 */
	public static void SendReInvite(Address addr, int accept, String username,
			String fullname, String keyChat)
	{
		_peer.SendReInvite(addr,accept,username,fullname, keyChat);
	}
	private static String getMessage(String[] temp) {
		String result = "";
		// i chay tu 2 đe lay ra message
		for (int i = 2; i < temp.length; i++) {
			if (i == temp.length - 1) {
				result = result + temp[i];
			} else {
				result = result + temp[i] + "/";
			}
		}
		return result;
	}

	/**
	 * 
	 * @param temp
	 * @return
	 */
	private static String getMessageGroup(String[] temp) {
		String result = "";
		// i chay tu 2 đe lay ra message
		for (int i = 1; i < temp.length; i++) {
			if (i == temp.length - 1) {
				result = result + temp[i];
			} else {
				result = result + temp[i] + "/";
			}
		}
		return result;
	}

	public static void SendInviteUpdateGroup(Address addr, CMember cmem)
	{
		_peer.SendInviteUpdateGroup(addr, cmem);
	}

	public static void SendInviteGroup(Address addr, String str)
	{
		_peer.SendInviteGroup(addr, str);
	}

	public static void SendSignoutGroup(Address addr, String keychat)
	{
		_peer.SendSignoutGroup(addr, keychat);
	}
	public static void SendSignoutInvite(Address addr, String keychat)
	{
		_peer.SendSignoutInvite(addr, keychat);
	}

	public static void sendFileChatPeer(Address addr, String fileName, String port)
	{
		Payload p = new Payload("sendfile");
		p.addParam("filename", fileName);
		p.addParam("portnumber", port);
		p.addParam("username", _userName);
		p.addParam("fullname", _fullName);
		_peer.sendFile(addr, p);
	}

	public static void sendFileChatGroup(String fileName, String keychat, int port, String type, ArrayList<Address> addrList)
	{
		Payload p = new Payload("sendfile");
		p.addParam("type", type);
		p.addParam("keychat", keychat);
		p.addParam("filename", fileName);
		p.addParam("portnumber", port);
		p.addParam("username", _userName);
		p.addParam("fullname", _fullName);
		for(int i = 0; i< addrList.size();i++)
		{
			_peer.sendFile(addrList.get(i), p);
		}
	}

	public static void RecevieFile(JSONObject params, Address addr) throws IOException
	{
		//lưu thông tin user xuống csdl
		Iterator<String> iter = params.keys();
		String fullNameSender = null;
		String userNameSender = null;
		String type = null;
		String keychat = null;
		String fName = null;
		String portNumber = null;
		String ipSender = addr.getHost() + ":" + addr.getPort();
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("fullname"))
			{
				fullNameSender = s;
			}
			else if(key.equals("username"))
			{
				userNameSender = s;
			}
			else if(key.equals("type"))
			{
				type = s;
			}
			else if(key.equals("keychat"))
			{
				keychat = s;
			}
			else if(key.equals("filename"))
			{
				fName = s;
			}
			else if(key.equals("portnumber"))
			{
				portNumber = s;
			}
		}
		//		ActivityController.ShowDialogReceiveFile(addr, userNameSender, fullNameSender, type, keychat, fName, portNumber);
		//thông báo lên giao diện chat
		if(type.equals("canhan"))//chatpeer
		{
			ReadWriteFileController.writeTXTPath(ReadWriteFileController.DIRECTORYCHATPEER + "Peer_"+userNameSender+"_Content.txt", "##file##:" + fullNameSender + "## gửi cho bạn 1 file ##" + fName + "##" + addr.getHost() + "##" + portNumber);
			ActivityController.handler.post(_runUpdateMsg);
		}
		else
		{
			if(type.equals("group"))
			{
				ReadWriteFileController.writeTXTPath(ReadWriteFileController.DIRECTORYCHATGROUP + "Group_"+keychat+"_grouping_Content.txt", "##file##:" + fullNameSender + "## gửi cho nhóm 1 file ##" + fName + "##" + addr.getHost() + "##" + portNumber);
				ActivityController.handler.post(_runUpdateMsgGroup);
				Log.d("PEERDROID","receive file chat group");	
			}
			else if(type.equals("invite"))
			{
				ReadWriteFileController.writeTXTPath(ReadWriteFileController.DIRECTORYCHATGROUP + "Group_"+keychat+"_Content.txt", "##file##:" + fullNameSender + "## gửi cho nhóm 1 file ##" + fName + "##" + addr.getHost() + "##" + portNumber);
				ActivityController.handler.post(_runUpdateMsgInvite);
				Log.d("PEERDROID","receive file chat invite");
			}
		}
	}
	/*------------Các hàm nhận thông tin teacher, class, subject, chapter, part, detailLearning------------*/
	public static void ReceiceTeacher(JSONObject params)
	{
		Iterator<String> iter = params.keys();
		int idteacher = 0;
		String teacherName = "";
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("teacher"))
			{
				String[] sArr = s.split("/");
				idteacher = Integer.valueOf(sArr[0]);
				teacherName = sArr[1];
			}
		}

		//insert teacher nếu chưa tồn tại
		TeacherDAO tDAO = new TeacherDAO(null);
		if(!tDAO.isExist(idteacher))
		{
			Log.d("PEERDROID","insert giao vien");
			TeacherDTO tDto = new TeacherDTO();
			tDto.set_ID(idteacher);
			tDto.set_Fullname(teacherName);
			if(tDAO.insertTeacher(tDto) == 0)
				Log.d("PEERDROID","insert giao vien that bai");
			else 
				Log.d("PEERDROID","insert giao vien thanh cong");
		}
	}

	public static void ReceiceID(JSONObject params)
	{
		String s=null;
		String str = null;
		Iterator<String> iter = params.keys();
		while(iter.hasNext()){			
			String key = iter.next();
			if(key.equals("learning"))
			{
				try {
					s = params.getString(key);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				str = s;
				//SynchronizedData(getNewID(s));
			}
			if(key.equals("idclass"))
			{
				try {
					s = params.getString(key);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Log.d("PEERDROID","IDclass: " + Integer.valueOf(s));
				NetworkController.set_idClass(Integer.valueOf(s));
			}
		}
		SynchronizedData(getNewID(str));
	}

	public static ArrayList<ArrayList<Object>> getNewID(String sLearning)
	{
		int idsubject = 0;
		int idchapter = 0;
		int idpart = 0;
		ArrayList<ArrayList<Object>> arrID = new ArrayList<ArrayList<Object>>();
		ArrayList<Object>	arrs = new ArrayList<Object>();
		ArrayList<Object>	arrp = new ArrayList<Object>();
		ArrayList<Object>	arrc = new ArrayList<Object>();
		ArrayList<Object>	arr = new ArrayList<Object>();
		String []sID = sLearning.split(getSeparator1());
		boolean bl = true;
		for(int i = 0;i<sID.length;i++)
		{
			bl = true;
			String []sS = sID[i].split(getSeparator());
			if(Integer.valueOf(sS[0]) != idsubject)
			{
				bl = false;
				if(arr.size()!=0)
				{
					arrs.add(arrp);
					arrc.add(arrs);
					arr.add(arrc);
					arrc = new ArrayList<Object>();
					arrp = new ArrayList<Object>();
					arrID.add(arr);
					arr = new ArrayList<Object>();
				}
				idsubject = Integer.valueOf(sS[0]);
				arr.add(idsubject);
				arrs = new ArrayList<Object>();
			}
			if(Integer.valueOf(sS[1]) != idchapter || bl == false)
			{
				if(arrs.size()!=0)
				{
					arrs.add(arrp);
					arrc.add(arrs);
					arrs = new ArrayList<Object>();
				}
				idchapter = Integer.valueOf(sS[1]);
				arrs.add(idchapter);
				arrp = new ArrayList<Object>();
			}
			idpart = Integer.valueOf(sS[2]);
			arrp.add(idpart);
		}
		if(arrs.size()>0)
		{
			arrs.add(arrp);
		}
		if(arr.size()>0)
		{
			arr.add(arrs);
			arrID.add(arr);
		}	
		return arrID;
	}

	public static void SynchronizedData(ArrayList<ArrayList<Object>> arrID)
	{
		int sizeSub = arrID.size();
		for(int i = 0; i < sizeSub; i++)
		{
			ArrayList<Object> Sub = arrID.get(i);
			int idsub = Integer.valueOf(Sub.get(0).toString());
			//System.out.print(idsub + " / ");

			ArrayList<Object> arrChap = (ArrayList<Object>)Sub.get(1);
			int sizeChap = arrChap.size();
			for(int j = 0; j < sizeChap; j++)
			{
				Object temp = arrChap.get(j);
				ChapterDAO cDao = new ChapterDAO(null);
				if(temp.toString().indexOf("[") != -1)
				{
					//Log.d("PEERDROID","Loai 1:");
					ArrayList<Object> Chap = (ArrayList<Object>)temp;
					int idChap = Integer.valueOf(Chap.get(0).toString());
					//Log.d("PEERDROID","id chap: " + idChap);
					if(cDao.isExist(idChap))
					{
						//Log.d("PEERDROID","da ton tai id chap: " + idChap);
						//kiểm tra part
						ArrayList<Object> arrPart = (ArrayList<Object>)Chap.get(1);
						int sizePart = arrPart.size();
						PartDAO pDao = new PartDAO(null);
						for(int k = 0; k < sizePart; k++)
						{
							if(!pDao.isExist(Integer.valueOf(arrPart.get(k).toString())))
							{
								//	Log.d("PEERDROID","id chap" + arrPart.get(k).toString());
								//gửi thông điệp lấy id part
								_peer.SendIDPartToTeacher(new Address(_ipHost), Integer.valueOf(arrPart.get(k).toString()), _idClass);
							}

						}
						System.out.println();
					}
					else
					{
						//	Log.d("PEERDROID","chua ton tai id chap: " + idChap);
						SubjectDAO sDao = new SubjectDAO(null);
						//id sub chưa tồn tại
						if(!sDao.isExist(idsub))
						{
							//gửi thông điệp lấy id sub, dừng kiểm tra chapter thuộc sub
							_peer.SendIDSubjectToTeacher(new Address(_ipHost), idsub, _idClass);
							break;
						}
						else
						{
							//gửi thông điệp lấy id chapter
							_peer.SendIDChapterToTeacher(new Address(_ipHost), idChap, _idClass);
						}
					}

				}
				else
				{
					//	Log.d("PEERDROID","loai 2");
					int idChap = Integer.valueOf(temp.toString());
					//Log.d("PEERDROID","ip chap: " + idChap);
					if(cDao.isExist(idChap))
					{
						//	Log.d("PEERDROID","da ton tai id chap: " + idChap);
						//kiểm tra part
						ArrayList<Object> arrPart = (ArrayList<Object>)arrChap.get(j+1);
						int sizePart = arrPart.size();
						PartDAO pDao = new PartDAO(null);
						for(int k = 0; k < sizePart; k++)
						{
							if(!pDao.isExist(Integer.valueOf(arrPart.get(k).toString())))
							{
								//gửi thông điệp lấy id part
								_peer.SendIDPartToTeacher(new Address(_ipHost), Integer.valueOf(arrPart.get(k).toString()), _idClass);
							}
						}
						System.out.println();
						break;
					}
					else
					{
						SubjectDAO sDao = new SubjectDAO(null);
						//id sub chưa tồn tại
						if(!sDao.isExist(idsub))
						{
							//gửi thông điệp lấy id sub, dừng kiểm tra chapter thuộc sub
							_peer.SendIDSubjectToTeacher(new Address(_ipHost), idsub, _idClass);
							break;
						}
						else
						{
							_peer.SendIDChapterToTeacher(new Address(_ipHost), idChap, _idClass);
							//gửi thông điệp lấy id chapter
						}
					}

				}
			}
		}

	}

	public static void ReceiveSubject(JSONObject params)throws NumberFormatException, JSONException
	{
		Iterator<String> iter = params.keys();
		SubjectDTO subDto = new SubjectDTO();
		int idteacher = 0;
		String teacherName = "";
		int idClass = 0;
		String strSubject="";
		boolean flag = false; //biến kiểm tra insert teacher thành công/thất bại
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("idclass"))
			{
				idClass = Integer.valueOf(s);
			}
			else if(key.equals("teacher"))
			{
				String[] sArr = s.split("/");
				idteacher = Integer.valueOf(sArr[0]);
				teacherName = sArr[1];
			}
			else if(key.equals("subject"))
			{
				strSubject = s;
			}
		}

		subDto = SubjectDTO.getSubject(strSubject, idteacher);
		//insert teacher nếu chưa tồn tại
		TeacherDAO tDAO = new TeacherDAO(null);
		if(!tDAO.isExist(idteacher))
		{
			TeacherDTO tDto = new TeacherDTO();
			tDto.set_ID(idteacher);
			tDto.set_Fullname(teacherName);
			if(tDAO.insertTeacher(tDto) == 0)
			{
				flag = true;
			}
		}

		//insert subject 
		if(!flag)
		{
			SubjectDAO sDao = new SubjectDAO(null);
			if(sDao.insertSubject(subDto) == 0)
			{
				Log.d("PEERDROID","insert Subject that bai");	
			}

			JoinSubjectClassDAO jscDao = new JoinSubjectClassDAO(null);
			if(jscDao.insertJoinSubjectClass(subDto.get_ID(), idClass)==0)
			{
				Log.d("PEERDROID","insert JoinSubjectClass that bai");		
			}
		}
		ActivityController.handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				FrmSubject.updateListAdapter();
			}
		});

	}

	public static void ReceiveChapter(JSONObject params)throws NumberFormatException, JSONException
	{
		Iterator<String> iter = params.keys();
		ChapterDTO chapDto = new ChapterDTO();
		int idSubject = 0;
		String strChapter = null;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("subject"))
			{
				idSubject = Integer.valueOf(s);
			}
			else if(key.equals("chapter"))
			{
				strChapter = s;

			}
		}
		chapDto = ChapterDTO.getChapter(strChapter, idSubject);

		//insert chapter
		ChapterDAO cDao = new ChapterDAO(null);
		cDao.insertChapter(chapDto);

	}

	public static void ReceivePart(JSONObject params)throws NumberFormatException, JSONException
	{
		Iterator<String> iter = params.keys();
		PartDTO partDto = new PartDTO();
		int idChapter = 0;
		String strPart = null;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("chapter"))
			{
				idChapter =Integer.valueOf(s);
			}
			else if(key.equals("part"))
			{
				strPart = s;

			}
		}

		partDto = PartDTO.getPart(strPart, idChapter);
		//insert part
		PartDAO pDao = new PartDAO(null);
		pDao.insertPart(partDto);
	}

	public static void ReceiveSubjectList(JSONObject params)throws NumberFormatException, JSONException
	{
		Iterator<String> iter = params.keys();
		ArrayList<SubjectDTO> subList = new ArrayList<SubjectDTO>();
		int idteacher = 0;
		String teacherName = "";
		int idClass = 0;
		String strSubject="";
		boolean flag = false;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("idclass"))
			{
				idClass = Integer.valueOf(s);
			}
			else if(key.equals("teacher"))
			{
				String[] sArr = s.split("/");
				idteacher = Integer.valueOf(sArr[0]);
				teacherName = sArr[1];
			}
			else if(key.equals("subject"))
			{
				strSubject = s;
			}
		}

		//gán chuổi s thành cấu trúc subject list
		subList = SubjectDTO.getSubjectList(strSubject, idteacher);
		//insert teacher nếu chưa tồn tại
		TeacherDAO tDAO = new TeacherDAO(null);
		if(!tDAO.isExist(idteacher))
		{
			TeacherDTO tDto = new TeacherDTO();
			tDto.set_ID(idteacher);
			tDto.set_Fullname(teacherName);
			if(tDAO.insertTeacher(tDto) == 0)
			{
				flag = true;
			}
		}

		//insert subject 
		if(!flag)
		{
			SubjectDAO sDao = new SubjectDAO(null);
			int n = subList.size();
			for(int i = 0; i < n; i++)
			{
				if(sDao.insertSubject(subList.get(i)) == 0)
				{
					Log.d("PEERDROID","insert subject thất bại");
				}
				JoinSubjectClassDAO jscDao = new JoinSubjectClassDAO(null);
				if(jscDao.insertJoinSubjectClass(subList.get(i).get_ID(), NetworkController._idClass)==0)
				{
					Log.d("PEERDROID","insert JoinSubjectClass that bai");		
				}
			}
		}		
		ActivityController.handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				FrmSubject.updateListAdapter();
			}
		});

	}

	public static void ReceiveChapterList(JSONObject params)throws NumberFormatException, JSONException
	{
		Iterator<String> iter = params.keys();
		ArrayList<ChapterDTO> chapList = new ArrayList<ChapterDTO>();
		int idSubject = 0;
		String strChapter = null;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("idsubject"))
			{

				idSubject = Integer.valueOf(s);
			}
			else if(key.equals("chapter"))
			{
				strChapter = s;
			}
		}
		chapList = ChapterDTO.getChapterList(strChapter, idSubject);

		//insert chapter
		ChapterDAO cDao = new ChapterDAO(null);
		int n = chapList.size();

		for(int i = 0; i < n; i++)
			if(cDao.insertChapter(chapList.get(i)) == 0)
				Log.d("PEERDROID","insert chap thất bại");
		FrmChapter.set_idSub(idSubject);
		ActivityController.handler.post(_runUpdateChapter);
		//		ActivityController.handler.post(new Runnable() {
		//
		//			@Override
		//			public void run() {
		//				// TODO Auto-generated method stub
		//				
		//				FrmChapter.updateListAdapter();
		//			}
		//		});

	}

	public static void ReceivePartList(JSONObject params)throws NumberFormatException, JSONException
	{
		Iterator<String> iter = params.keys();
		ArrayList<PartDTO> partList = new ArrayList<PartDTO>();
		int idChapter = 0;
		String strPart = null;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("idchapter"))
			{
				idChapter =Integer.valueOf(s);
			}
			else if(key.equals("part"))
			{
				strPart = s;

			}
		}

		partList = PartDTO.getPartList(strPart, idChapter);
		//insert part
		PartDAO pDao = new PartDAO(null);
		int n = partList.size();
		for(int i = 0; i < n; i++)
		{
			if(pDao.insertPart(partList.get(i))==0)
			{
				Log.d("PEERDROID","insert Part that bai");
			}
		}
		FrmPart.set_idChap(idChapter);
		ActivityController.handler.post(_runUpdatePart);
		//		ActivityController.handler.post(new Runnable() {
		//
		//			@Override
		//			public void run() {
		//				// TODO Auto-generated method stub
		//				FrmPart.updateListAdapter();
		//			}
		//		});
	}

	public static void ReceiveDetailLearning(JSONObject params)throws NumberFormatException, JSONException
	{
		Iterator<String> iter = params.keys();
		DetailLearningDTO dlDto = new DetailLearningDTO();
		int idClass = 0;
		int idPart = 0;
		String strDetailLearning = null;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("idclass"))
			{
				idClass =Integer.valueOf(s);
				Log.d("PEERDROID","id class:" + idClass);
			}
			else if(key.equals("idpart"))
			{
				idPart = Integer.valueOf(s);
			}
			else if(key.equals("detaillearning"))
			{
				strDetailLearning = s;
			}
		}

		dlDto = DetailLearningDTO.getDetailLearning(strDetailLearning, idPart, idClass);
		//insert detailLearning
		DetailLearningDAO dlDao = new DetailLearningDAO(null);
		if(!dlDao.isExist(dlDto.get_ID()))
		{
			if(dlDao.insertDetailLearning(dlDto)==0)
				Log.d("PEERDROID","insert detailLearrning thai bai");
		}
	}

	public static void SendMessageRequestExercises(Address addr){
		_peer.SendMessageRequestExercises(addr);
	}

	/*-----------------------cac ham xu ly khi nhan thong tin yeu cau bai tap----------*/
	public static void SendTestExercire(Address addr, CUsingQuestionList cUsingQ, String idexercises){

		_peer.SendMessageFullTest(addr, cUsingQ,idexercises);

	}
	//-----ham lay danhs sach bai tap hien thoi--------------
	public static CUsingQuestionList getUsingQuestionList(){
		CUsingQuestionList listtest = new CUsingQuestionList();
		//lay ra usingq hien tai
		String namenewtest = ReadWriteFileController.DIRECTORYTEST + "testList.xml";
		String fileNameNewTest = ReadXML.ReadTestNew(namenewtest);

		String path = ReadWriteFileController.DIRECTORY + fileNameNewTest + ".xml";
		Document doc = null;
		listtest=ReadXML.ReadReceive(doc, path);


		return listtest;
	}

	public static String getIdExercises(){
		String namenewtest = ReadWriteFileController.DIRECTORYTEST + "testList.xml";
		String fileNameNewTest = ReadXML.ReadTestNew(namenewtest);
		String result = null;
		String[] arr = fileNameNewTest.split("_");
		result=arr[1];
		return result;
	}


	/*-----------------------các hàm module đồng bộ-------------------------------*/
	public static void SynchronizedDatabase(int id, int IDTypeTopic, int IDUpdateType, int IDTopic, String sContent)
	{
		Log.d("PEERDROID","vao SynchronizedDatabase");
		UpdateListDAO ulDao = new UpdateListDAO(null);
		ulDao.deleteUpdateList(IDTopic, IDTypeTopic);
		if(ulDao.insertUpdateList(id, IDTypeTopic, IDTopic, IDUpdateType, sContent, false) == 1)
			Log.d("PEERDROID","insert updatelist thanh cong:");
		Log.d("PEERDROID","sau insert updateList");
		switch (IDTypeTopic) {
		case 1://subject
		{	
			Log.d("PEERDROID","vao syschr subject");
			if(IDUpdateType == 1)//insert
			{
				SendRequestSubject(_ipHost, id, IDTopic, IDUpdateType);
				break;
			}
			SubjectDAO sDao = new SubjectDAO(null);
			if(sDao.isExist(IDTopic))//tồn tại
			{
				if(IDUpdateType == 2)//xoá
				{
					if(sDao.deleteSubject(IDTopic)== 1)
						Log.d("PEERDROID","xoa sub thanh cong");	
				}
				else//update 
				{
					SendRequestSubject(_ipHost, id, IDTopic, IDUpdateType);
				}
			}
			break;
		}
		case 2: //chapter
		{
			Log.d("PEERDROID","vao syschr chap");
			if(IDUpdateType == 1)//insert
			{
				SendRequestChapter(_ipHost, id, IDTopic, IDUpdateType);
				break;
			}
			ChapterDAO cDao = new ChapterDAO(null);
			if(cDao.isExist(IDTopic))//tồn tại
			{
				if(IDUpdateType == 2)//xoá
				{
					if(cDao.deleteChapter(IDTopic)== 1)
						Log.d("PEERDROID","xoa chap thanh cong");	
				}
				else//update 
				{
					SendRequestChapter(_ipHost, id, IDTopic, IDUpdateType);
				}
			}
			break;

		}
		case 3: //part
		{
			Log.d("PEERDROID","vao syschr part");
			if(IDUpdateType == 1)//insert
			{
				SendRequestPart(_ipHost, id, IDTopic, IDUpdateType);
				break;
			}
			PartDAO pDao = new PartDAO(null);
			if(pDao.isExist(IDTopic))//tồn tại
			{
				if(IDUpdateType == 2)//xoá
				{
					if(pDao.deletePart(IDTopic)== 1)
						Log.d("PEERDROID","xoa part thanh cong");	
				}
				else//update 
				{
					SendRequestPart(_ipHost, id, IDTopic, IDUpdateType);
				}
			}
			break;
		}
		case 4: //detaillearning
		{
			Log.d("PEERDROID","vao syschr detail");
			if(IDUpdateType == 1)//insert
			{
				SendRequestDetailLearning(_ipHost, id, IDTopic, IDUpdateType);
				break;
			}
			DetailLearningDAO dlDao = new DetailLearningDAO(null);
			if(dlDao.isExist(IDTopic))//tồn tại
			{
				if(IDUpdateType == 2)//xoá
				{
					if(dlDao.deleteDetailLearning(IDTopic)== 1)
						Log.d("PEERDROID","xoa detail thanh cong");	
				}
				else//update 
				{
					SendRequestDetailLearning(_ipHost, id, IDTopic, IDUpdateType);
				}
			}
			break;
		}
		case 5: //exercise
		{
			String pathTestList = ReadWriteFileController.DIRECTORYTEST + "testList.xml";
			ArrayList<Object> result = ReadWriteFileController.isExistTestInTestList(IDTopic, pathTestList);
			if(result.size() == 5)//đủ thông tin
			{
				if(IDUpdateType == 2)//xoá
				{
					ReadWriteFileController.deleteFile(ReadWriteFileController.DIRECTORYTESTCONTENT + result.get(4)+ ".xml");
					ReadWriteFileController.deleteTestList(pathTestList, Integer.valueOf(result.get(1).toString()), Integer.valueOf(result.get(0).toString()), Integer.valueOf(result.get(2).toString()));
				}
				else//insert, update 
				{
					SendRequestExercises(_ipHost, IDTopic, Integer.valueOf(result.get(0).toString()), result.get(3).toString(), Integer.valueOf(result.get(2).toString()), IDUpdateType);
				}
			}
			break;

		}
		case 6: //question
		{
			break;

		}
		}
	}
	//hàm nhận thông tin updatelist - danh sách các thông tin được cập nhật từ giáo viên
	public static void ReceiveUpdateList(JSONObject params) throws JSONException
	{
		Iterator<String> iter = params.keys();
		String update = "";
		int idmax = 0;
		while(iter.hasNext()){
			String key = (String) iter.next();

			if(key.equals("update"))
			{
				update =  params.getString(key);
			}
			else if(key.equals("idmax"))
			{
				idmax =  params.getInt(key);
			}
		}
		String []listupdate = update.split(SEPARATOR1);
		UpdateListDAO ulDao = new UpdateListDAO(null);
		for(int i = 0; i< listupdate.length; i++)
		{
			String[]OneUpdate = listupdate[i].split(SEPARATOR);
			if(OneUpdate.length!=0)
				if(OneUpdate.length== 5)
				{
					SynchronizedDatabase(Integer.valueOf(OneUpdate[0]), Integer.valueOf(OneUpdate[1]), Integer.valueOf(OneUpdate[2]), Integer.valueOf(OneUpdate[3]), OneUpdate[4]);
				} 
				else{
					SynchronizedDatabase(Integer.valueOf(OneUpdate[0]), Integer.valueOf(OneUpdate[1]), Integer.valueOf(OneUpdate[2]), Integer.valueOf(OneUpdate[3]), "");
				}
		}
	}
	public static void SendUpdateList()
	{
		Payload p = new Payload();
		Address addr = new Address("");
		//to do something

		_peer.SendUpdateList(addr, p);
	}

	public static void ReceiveUpdateListNow(JSONObject params) throws JSONException
	{
		Iterator<String> iter = params.keys();
		String update = "";
		int idmax = 0;
		while(iter.hasNext()){
			String key = (String) iter.next();

			if(key.equals("update"))
			{
				update =  params.getString(key);
			}
			else if(key.equals("idmax"))
			{
				idmax =  params.getInt(key);
			}
		}
		String []listupdate = update.split(SEPARATOR1);
		Log.d("PEERDROID","list update: " + listupdate + " size:" + listupdate.length);
		UpdateListDAO ulDao = new UpdateListDAO(null);
		for(int i = 0; i< listupdate.length; i++)
		{
			String[]OneUpdate = listupdate[i].split(SEPARATOR);
			Log.d("PEERDROID","one update: " + OneUpdate+ " size:" + OneUpdate.length);
			if(OneUpdate.length!=0)
				if(OneUpdate.length== 5)
				{
					Log.d("PEERDROID","dong bo");
					SynchronizedDatabase(Integer.valueOf(OneUpdate[0]), Integer.valueOf(OneUpdate[1]), Integer.valueOf(OneUpdate[2]), Integer.valueOf(OneUpdate[3]), OneUpdate[4]);
				} 
				else{
					SynchronizedDatabase(Integer.valueOf(OneUpdate[0]), Integer.valueOf(OneUpdate[1]), Integer.valueOf(OneUpdate[2]), Integer.valueOf(OneUpdate[3]), "");
				}
		}
	}
	//nhận idmax học viên
	public static void ReceiveIDMax(JSONObject params) throws JSONException
	{
		//		Iterator<String> iter = params.keys();
		//		int idmax = 0;
		//		while(iter.hasNext()){
		//			String key = (String) iter.next();
		//			if(key.equals("idmax"))
		//			{
		//				idmax =  params.getInt(key);
		//			}
		//		}
		//		UpdateListDAO updateListDAO = new UpdateListDAO(null);
		//		updateListDAO.insertUpdateList(idmax, 0, 0, 0, "", false);
	}
	public static void SendIDMax(Address addr)
	{
		Payload p = new Payload();
		UpdateListDAO dlDao = new UpdateListDAO(null);
		dlDao.getIDMax();
		int idmax=dlDao.getIDMax();
		//to do something
		p.addParam("idmax", idmax);
		p.addParam("idlearner", NetworkController.get_idLearner());
		p.addParam("idclass", NetworkController.get_idClass());
		_peer.SendIDMax(addr, p);
	}

	public static void ReceiveUpdateSubject(JSONObject params)
	{
		//nhận được thông tin update, lưu vào csdl:
		Log.d("PEERDROID","vao ham nhan ReceiveUpdateSubject");
		Iterator<String> iter = params.keys();
		ArrayList<ArrayList<Object>> resList = new ArrayList<ArrayList<Object>>();
		int id = 0;
		String subject = "";
		String teacher = "";
		int idUpdateType = 0;
		SubjectDAO sDao = new SubjectDAO(null);
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("id"))
			{
				id = Integer.valueOf(s);
			}
			else if(key.equals("teacher"))
			{
				teacher = s;
			}
			else if(key.equals("subject"))
			{
				subject = s;
			}
			else if(key.equals("idupdatetype"))
			{
				idUpdateType = Integer.valueOf(s);
			}
		}
		//lưu csdl:

		//lấy thông tin giáo viên:
		String[] temp = teacher.split(SEPARATOR);
		int idTeacher = Integer.valueOf(temp[0]);

		//gán chuổi s thành cấu trúc subject list
		SubjectDTO sDto = SubjectDTO.getSubject(subject, idTeacher);
		if(idUpdateType == 3) //cập nhật thông tin
		{
			sDao.updateSubject(sDto);
		}
		else if(idUpdateType == 1)//thêm thông tin
		{
			if(sDao.insertSubject(sDto) == 0)
			{
				Log.d("PEERDROID","insert subject thất bạ=====================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================");
			}
			JoinSubjectClassDAO jscDao = new JoinSubjectClassDAO(null);
			if(jscDao.insertJoinSubjectClass(sDto.get_ID(), NetworkController._idClass)==0)
			{
				Log.d("PEERDROID","insert JoinSubjectClass that bai");		
			}
		}

		//cập nhật bảng UpdateList
		UpdateListDAO ulDao = new UpdateListDAO(null);
		ulDao.updateActive(id, true);
		
		ActivityController.handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				FrmSubject.updateListAdapter();
			}
		});
	}
	//gửi thông tin subject được yêu cầu.
	public static void SendUpdateSubject(String address, int id, int idSubject, int idclass, int idupdatetype)
	{
		Payload p = new Payload();
		Address addr = new Address(address);
		//to do something

		SubjectDAO sDao = new SubjectDAO(null);
		TeacherDAO tDao = new TeacherDAO(null);

		//lấy dữ liệu teacher từ bảng theo cấu trúc: 
		int idTeacher = sDao.getTeacher(idSubject);
		String fullNameTeacher = tDao.getFullNameTeacher(idTeacher);
		String infoTeacher = idTeacher + SEPARATOR + fullNameTeacher;
		p.addParam("teacher", infoTeacher);
		//lấy dữ liệu từ bảng subject theo cấu trúc:
		SubjectDTO sDto = sDao.getSubject(idSubject);
		String infoSubject = sDto.get_ID() + SEPARATOR + sDto.get_Name() + SEPARATOR + sDto.get_Note() + SEPARATOR + sDto.get_Content() + SEPARATOR + 0;
		p.addParam("subject", infoSubject);
		p.addParam("idupdatetype", idupdatetype);
		p.addParam("id", id);
		_peer.SendUpdateSubject(addr, p);
	}
	public static void ReceiveRequestSubject(JSONObject params, Address sender)
	{
		//nhận thông tin yêu cầu từ user khác
		//kiểm tra xem có thông tin phù hợp? --> có --> gửi phản hồi
		Log.d("PEERDROID","vao ham nhan ReceiveRequestSubject");
		Iterator<String> iter = params.keys();
		ArrayList<ArrayList<Object>> resList = new ArrayList<ArrayList<Object>>();
		int id = 0;
		int idSubject = 0;
		int idClass = 0;
		int idUpdateType = 0;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("id"))
			{
				id = Integer.valueOf(s);
			}
			else if(key.equals("idsubject"))
			{
				idSubject = Integer.valueOf(s);
			}
			else if(key.equals("idclass"))
			{
				idClass = Integer.valueOf(s);
			}
			else if(key.equals("idupdatetype"))
			{
				idUpdateType = Integer.valueOf(s);
			}
		}
		//kiểm tra:
		UpdateListDAO ulDao = new UpdateListDAO(null);
		boolean active = ulDao.getActive(id);
		if(active)
		{
			String address = sender.getHost() + ":" + sender.getPort();
			SendUpdateSubject(address, id, idSubject, idClass, idUpdateType);
		}
	}
	//send yêu cầu gửi thông tin subject
	public static void SendRequestSubject(String address, int id, int idsubject, int idupdate )
	{
		Payload p = new Payload();
		Address addr = new Address(address);
		//to do something
		p.addParam("idsubject", idsubject);
		p.addParam("idupdatetype", idupdate);
		p.addParam("idclass", NetworkController.get_idClass());
		p.addParam("id", id);
		_peer.SendRequestSubject(addr, p);
	}

	public static void ReceiveUpdateChapter(JSONObject params)
	{
		//nhận được thông tin update, lưu vào csdl:
		Log.d("PEERDROID","vao ham nhan ReceiveUpdateSubject");
		Iterator<String> iter = params.keys();
		ArrayList<ArrayList<Object>> resList = new ArrayList<ArrayList<Object>>();
		int id = 0;
		int  idSubject = 0;
		String chapter = "";
		int idUpdateType = 0;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("id"))
			{
				id = Integer.valueOf(s);
			}
			else if(key.equals("idsubject"))
			{
				idSubject = Integer.valueOf(s);
			}
			else if(key.equals("chapter"))
			{
				chapter = s;
			}
			else if(key.equals("idupdatetype"))
			{
				idUpdateType = Integer.valueOf(s);
			}
		}
		//lưu csdl:
		//lấy thông tin chapter
		ChapterDTO cDto = ChapterDTO.getChapter(chapter, idSubject);
		ChapterDAO cDao = new ChapterDAO(null);
		if(idUpdateType == 3)//update
		{
			cDao.updateChapter(cDto);
		}
		else if(idUpdateType == 1)//insert
		{
			cDao.insertChapter(cDto);
		}
		//cập nhật bảng UpdateList
		UpdateListDAO ulDao = new UpdateListDAO(null);
		ulDao.updateActive(id, true);
		
		FrmChapter.set_idSub(idSubject);
		ActivityController.handler.post(_runUpdateChapter);
	}
	public static void SendUpdateChapter(String address, int id, int idchapter, int idclass, int idupdatetype)
	{
		Payload p = new Payload();
		Address addr = new Address(address);
		//to do something
		ChapterDAO cDao = new ChapterDAO(null);
		ChapterDTO cDto = cDao.getChapter(idchapter);
		//lấy idsubject từ bảng chapter
		int idSubject = cDto.get_IDSubject();
		p.addParam("idsubject", idSubject);
		//lấy dữ liệu chapter từ bảng chapter theo cấu trúc:
		String infoChapter = cDto.get_ID() + SEPARATOR + cDto.get_Name() + SEPARATOR + cDto.get_Note() + SEPARATOR + cDto.get_ContentAbstract() + SEPARATOR + 0;
		p.addParam("chapter", infoChapter);
		p.addParam("idupdatetype", idupdatetype);
		p.addParam("id", id);

		_peer.SendUpdateChapter(addr, p);
	}
	public static void ReceiveRequestChapter(JSONObject params, Address sender)
	{
		//nhận thông tin yêu cầu từ user khác
		//kiểm tra xem có thông tin phù hợp? --> có --> gửi phản hồi
		Log.d("PEERDROID","vao ham nhan ReceiveRequestSubject");
		Iterator<String> iter = params.keys();
		ArrayList<ArrayList<Object>> resList = new ArrayList<ArrayList<Object>>();
		int id = 0;
		int idChapter = 0;
		int idClass = 0;
		int idUpdateType = 0;
		while(iter.hasNext()){
			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("id"))
			{
				id = Integer.valueOf(s);
			}
			else if(key.equals("idchapter"))
			{
				idChapter = Integer.valueOf(s);
			}
			else if(key.equals("idclass"))
			{
				idClass = Integer.valueOf(s);
			}
			else if(key.equals("idupdatetype"))
			{
				idUpdateType = Integer.valueOf(s);
			}
		}
		//kiểm tra:
		UpdateListDAO ulDao = new UpdateListDAO(null);
		boolean active = ulDao.getActive(id);
		if(active)
		{
			String address = sender.getHost() + ":" + sender.getPort();
			SendUpdateChapter(address, id, idChapter, idClass, idUpdateType);
		}
	}
	public static void SendRequestChapter(String address, int id, int idchapter, int idupdate)
	{
		Payload p = new Payload();
		Address addr = new Address(address);
		//to do something
		p.addParam("idchapter", idchapter);
		p.addParam("idupdatetype", idupdate);
		p.addParam("idclass", NetworkController.get_idClass());
		p.addParam("id", id);

		_peer.SendRequestChapter(addr, p);
	}

	public static void ReceiveUpdatePart(JSONObject params)
	{
		//nhận được thông tin update, lưu vào csdl:
		Log.d("PEERDROID","vao ham nhan ReceiveUpdatePart");
		Iterator<String> iter = params.keys();
		ArrayList<ArrayList<Object>> resList = new ArrayList<ArrayList<Object>>();
		int id = 0;
		int  idChapter = 0;
		String part = "";
		int idUpdateType = 0;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("id"))
			{
				id = Integer.valueOf(s);
				Log.d("PEERDROID","idmax : " + id);
			}
			else if(key.equals("idchapter"))
			{
				idChapter = Integer.valueOf(s);
			}
			else if(key.equals("part"))
			{
				part = s;
			}
			else if(key.equals("idupdatetype"))
			{
				idUpdateType = Integer.valueOf(s);
				Log.d("PEERDROID","idupdatetype : " + idUpdateType);
			}
		}
		//lưu csdl:
		//lấy thông tin part
		PartDTO pDto = PartDTO.getPart(part, idChapter);
		PartDAO pDao = new PartDAO(null);

		if(idUpdateType == 3)//update
		{
			Log.d("PEERDROID","cap nhat part:" + pDto.get_ID() + "_" + pDto.get_Name());
			if(pDao.updatePart(pDto)==1)
				Log.d("PEERDROID","cap nhat part thanh cong:");
		}
		else if(idUpdateType == 1)//insert
		{
			Log.d("PEERDROID","insert part: ");
			pDao.insertPart(pDto);
		}
		//cập nhật bảng UpdateList
		UpdateListDAO ulDao = new UpdateListDAO(null);
		ulDao.updateActive(id, true);
		
		FrmPart.set_idChap(idChapter);
		ActivityController.handler.post(_runUpdatePart);
	}
	public static void SendUpdatePart(String address, int id, int idPart, int idclass, int idupdatetype)
	{
		Payload p = new Payload();
		Address addr = new Address(address);
		//to do something
		PartDAO pDao = new PartDAO(null);
		PartDTO pDto = pDao.getPart(idPart);
		//lấy thông tin idchapter từ bảng part:
		int idChapter = pDto.get_IDChapter();
		p.addParam("idchapter", idChapter);
		//lấy thông tin part từ bảng part theo cấu trúc:
		String infoPart = pDto.get_ID() + SEPARATOR + pDto.get_Name() + SEPARATOR + pDto.get_Note() + SEPARATOR + pDto.get_Content() + SEPARATOR + 0;
		p.addParam("part", infoPart);
		p.addParam("idupdatetype", idupdatetype);
		p.addParam("id", id);

		_peer.SendUpdatePart(addr, p);
	}
	public static void ReceiveRequestPart(JSONObject params, Address sender)
	{
		//nhận thông tin yêu cầu từ user khác
		//kiểm tra xem có thông tin phù hợp? --> có --> gửi phản hồi
		Log.d("PEERDROID","vao ham nhan ReceiveRequestSubject");
		Iterator<String> iter = params.keys();
		ArrayList<ArrayList<Object>> resList = new ArrayList<ArrayList<Object>>();
		int id = 0;
		int idPart = 0;
		int idClass = 0;
		int idUpdateType = 0;
		while(iter.hasNext()){
			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("id"))
			{
				id = Integer.valueOf(s);
			}
			else if(key.equals("idpart"))
			{
				idPart = Integer.valueOf(s);
			}
			else if(key.equals("idclass"))
			{
				idClass = Integer.valueOf(s);
			}
			else if(key.equals("idupdatetype"))
			{
				idUpdateType = Integer.valueOf(s);
			}
		}
		//kiểm tra:
		UpdateListDAO ulDao = new UpdateListDAO(null);
		boolean active = ulDao.getActive(id);
		if(active)
		{
			String address = sender.getHost() + ":" + sender.getPort();
			SendUpdatePart(address, id, idPart, idClass, idUpdateType);
		}
	}
	public static void SendRequestPart(String address, int id, int idpart, int idupdate)
	{
		Payload p = new Payload();
		Address addr = new Address(address);
		//to do something
		p.addParam("idpart", idpart);
		p.addParam("idupdatetype", idupdate);
		p.addParam("idclass", NetworkController.get_idClass());
		p.addParam("id", id);
		_peer.SendRequestPart(addr, p);
	}

	public static void ReceiveUpdateDetailLearning(JSONObject params)
	{
		//nhận được thông tin update, lưu vào csdl:
		Log.d("PEERDROID","vao ham nhan ReceiveUpdatePart");
		Iterator<String> iter = params.keys();
		ArrayList<ArrayList<Object>> resList = new ArrayList<ArrayList<Object>>();
		int id = 0;
		int  idPart = 0;
		int  idClass = 0;
		String detailLearning = "";
		int idUpdateType = 0;
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("id"))
			{
				id = Integer.valueOf(s);
			}
			else if(key.equals("idpart"))
			{
				idPart = Integer.valueOf(s);
			}
			else if(key.equals("idclass"))
			{
				idClass = Integer.valueOf(s);
			}
			else if(key.equals("detaillearning"))
			{
				detailLearning = s;
			}
			else if(key.equals("idupdatetype"))
			{
				idUpdateType = Integer.valueOf(s);
			}
		}
		//lấy thông tin part
		DetailLearningDTO dlDto = DetailLearningDTO.getDetailLearning(detailLearning, idPart, idClass);
		DetailLearningDAO dlDao = new DetailLearningDAO(null);
		if(idUpdateType == 3)//update
		{
			dlDao.updateDetailLearning(dlDto);
		}
		else if(idUpdateType == 1)//insert
		{
			dlDao.insertDetailLearning(dlDto);
		}
		//cập nhật bảng UpdateList
		UpdateListDAO ulDao = new UpdateListDAO(null);
		ulDao.updateActive(id, true);
	}
	public static void SendUpdateDetailLearning(String address, int id, int iddetaillearning, int idupdatetype)
	{
		Payload p = new Payload();
		Address addr = new Address("");
		//to do something
		DetailLearningDAO dlDao = new DetailLearningDAO(null);
		DetailLearningDTO dlDto = dlDao.getDetailLearningID(iddetaillearning);
		//lấy idpart
		int idPart = dlDto.get_IDPart();
		p.addParam("idpart", idPart);
		//lấy idclass
		int idClass = dlDto.get_IDClass();
		p.addParam("idclass", idClass);
		//lấy dữ liệu detailLearning từ bảng detailLearning theo cấu trúc:
		String infoDetailLearning = dlDto.get_ID() + SEPARATOR + dlDto.get_DateLearning().toString() + dlDto.get_IDFeelType();
		p.addParam("detaillearning", infoDetailLearning);
		p.addParam("idupdatetype", idupdatetype);
		p.addParam("id", id);


		_peer.SendUpdateDetailLearning(addr, p);
	}
	public static void ReceiveRequestDetailLearning(JSONObject params, Address sender)
	{
		//nhận thông tin yêu cầu từ user khác
		//kiểm tra xem có thông tin phù hợp? --> có --> gửi phản hồi
		Log.d("PEERDROID","vao ham nhan ReceiveRequestSubject");
		Iterator<String> iter = params.keys();
		ArrayList<ArrayList<Object>> resList = new ArrayList<ArrayList<Object>>();
		int id = 0;
		int idDetailLearning = 0;
		int idUpdateType = 0;
		while(iter.hasNext()){
			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("id"))
			{
				id = Integer.valueOf(s);
			}
			else if(key.equals("iddetaillearning"))
			{
				idDetailLearning = Integer.valueOf(s);
			}
			else if(key.equals("idupdatetype"))
			{
				idUpdateType = Integer.valueOf(s);
			}
		}
		//kiểm tra:
		UpdateListDAO ulDao = new UpdateListDAO(null);
		boolean active = ulDao.getActive(id);
		if(active)
		{
			String address = sender.getHost() + ":" + sender.getPort();
			SendUpdateDetailLearning(address, id, idDetailLearning, idUpdateType);
		}
	}
	public static void SendRequestDetailLearning(String address, int id, int iddetaillearning, int idupdate)
	{
		Payload p = new Payload();
		Address addr = new Address(address);
		//to do something
		p.addParam("idupdatetype", idupdate);
		p.addParam("iddetaillearning", iddetaillearning);
		p.addParam("id", id);

		_peer.SendRequestDetailLearning(addr, p);

	}

	public static void ReceiveUpdateExercises(JSONObject params)
	{
		//nhận được thông tin update, lưu vào csdl:
		Log.d("PEERDROID","vao ham nhan ReceiveUpdatePart");
		Iterator<String> iter = params.keys();
		ArrayList<ArrayList<Object>> resList = new ArrayList<ArrayList<Object>>();
		int id = 0;
		String detailLearning = "";
		ArrayList<CQuestion> questionList = new ArrayList<CQuestion>();
		int idUpdateType = 0;
		int idDetailLearning = 0;
		int idExercise = 0;
		String nameExercise = "";
		String nameExerciseOld = "";
		long beginTime = 0;
		long workTime = 0;

		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("id"))
			{
				id  = Integer.valueOf(s);
			}
			else if(key.equals("nameexercises"))
			{
				//tên title mới -- lưu xuống file xml
				nameExercise = s;
			}
			else if(key.equals("time"))//thời gian bắt đầu
			{
				beginTime = Long.valueOf(s);
			}
			else if(key.equals("workingtime"))//thời gian làm bài
			{
				workTime = Long.valueOf(s);
			}
			else if(key.equals("iddetaillearning"))
			{
				idDetailLearning = Integer.valueOf(s);
			}
			else if(key.equals("idexercises"))
			{
				idExercise = Integer.valueOf(s);
			}
			else if(key.equals("nameexercisesold"))
			{
				//title cũ -- lưu xuống csdl
				nameExerciseOld = s;
			}
			else if(key.equals("idupdatetype"))
			{
				idUpdateType = Integer.valueOf(s);
			}
			else
			{
				String[] sArr = s.split(SEPARATOR);
				if (sArr.length > 2) {
					// XuatCauHoi(sArr);
					CQuestion ques = CQuestion.getQuestion(sArr);
					questionList.add(ques);
				}
			}
		}
		//lưu csdl:
		//lấy thông tin part
		DetailLearningDAO dlDao = new DetailLearningDAO(null);
		int idPart = dlDao.getIDPart(idDetailLearning);
		String fnameTest = idPart + "_" + idExercise + "_FullTest_" + idDetailLearning + ".xml";
		String path = ReadWriteFileController.DIRECTORYTESTCONTENT + fnameTest;
		ReadWriteFileController.WriteExercise(path, nameExercise, idExercise, idPart, idDetailLearning, beginTime, workTime, questionList);
		ReadWriteFileController.WriteTestList(idPart, idDetailLearning, nameExercise, fnameTest);

		//cập nhật bảng UpdateList
		UpdateListDAO ulDao = new UpdateListDAO(null);
		ulDao.updateActive(id, true);
		ulDao.updateContent(id, nameExerciseOld);
	}
	public static void SendUpdateExercises(int id, int iddetaillearning, String Nameex, int idexercises, int idupdatetype)
	{
		Payload p = new Payload();
		Address addr = new Address("");
		//to do something
		//lấy iddetailLearning, nameexercises, time, workingtime từ file xml
		DetailLearningDAO dlDao = new DetailLearningDAO(null);
		int idPart = dlDao.getIDPart(iddetaillearning);
		String fName = idPart+"_"+idexercises+"_FullTest_"+iddetaillearning;
		String path = ReadWriteFileController.DIRECTORYTESTCONTENT + fName;
		ArrayList<Object> arr= ReadXML.ReadInfoExercises(path);
		p.addParam("iddetaillearning", iddetaillearning);
		p.addParam("nameexercises", arr.get(3).toString());
		p.addParam("time", arr.get(1).toString());
		p.addParam("workingtime",ReadWriteFileController.ConvertTimeToString(Long.valueOf(arr.get(2).toString())));
		p.addParam("nameexercisesold", Nameex);
		p.addParam("idupdatetype", idupdatetype);
		p.addParam("id", id);
		_peer.SendUpdateExercises(addr, p);
	}
	public static void ReceiveRequestExercises(JSONObject params, Address sender)
	{
		//nhận thông tin yêu cầu từ user khác
		//kiểm tra xem có thông tin phù hợp? --> có --> gửi phản hồi
		Log.d("PEERDROID","vao ham nhan ReceiveRequestSubject");
		Iterator<String> iter = params.keys();
		ArrayList<ArrayList<Object>> resList = new ArrayList<ArrayList<Object>>();
		int id = 0;
		int idDetailLearning = 0;
		int idExercise = 0;
		String nameExercise = "";
		int idUpdateType = 0;
		while(iter.hasNext()){
			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("id"))
			{
				id = Integer.valueOf(s);
			}
			else if(key.equals("iddetaillearning"))
			{
				idDetailLearning = Integer.valueOf(s);
			}
			else if(key.equals("nameexercises"))
			{
				nameExercise = s;
			}
			else if(key.equals("idexercises"))
			{
				idExercise = Integer.valueOf(s);
			}
			else if(key.equals("idupdatetype"))
			{
				idUpdateType = Integer.valueOf(s);
			}
		}
		//kiểm tra:
		UpdateListDAO ulDao = new UpdateListDAO(null);
		boolean active = ulDao.getActive(id);
		if(active)
		{
			String address = sender.getHost() + ":" + sender.getPort();
			SendUpdateExercises(id, idDetailLearning, nameExercise, idExercise, idUpdateType);
		}
	}
	public static void SendRequestExercises(String address, int id, int iddetaillearning, String Nameex, int idexercises, int idupdate)
	{
		Payload p = new Payload();
		Address addr = new Address(address);
		//to do something
		p.addParam("idupdatetype", idupdate);
		p.addParam("iddetaillearning", iddetaillearning);
		p.addParam("nameexercises", Nameex);
		p.addParam("idexercises", idexercises);
		p.addParam("id", id);


		_peer.SendRequestExercises(addr, p);
	}

	public static void ReceiveUpdateQuestion(JSONObject params)
	{
		//nhận được thông tin update, lưu vào csdl:
		Log.d("PEERDROID","vao ham nhan ReceiveUpdatePart");
		Iterator<String> iter = params.keys();
		ArrayList<ArrayList<Object>> resList = new ArrayList<ArrayList<Object>>();
		int idupdatetype = 0;
		String question = "";
		while(iter.hasNext()){

			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("idupdatetype"))
			{
				idupdatetype = Integer.valueOf(s);
			}
			else if(key.equals("question"))
			{
				question = s;
			}
		}
		//lưu csdl:
		String sArr[] = question.split(SEPARATOR);
		CQuestion ques = CQuestion.getQuestion(sArr);
		ReadWriteFileController.UpdateQuestion(ques);

		//cập nhật bảng UpdateList
		//		UpdateListDAO ulDao = new UpdateListDAO(null);
		//		ulDao.updateActive(id, true);
		//		ulDao.updateContent(id, nameExerciseOld);
	}
	public static void SendUpdateQuestion(String address, int idquestion, int idupdatetype)
	{
		Payload p = new Payload();
		Address addr = new Address(address);
		//to do something
		//lấy thông tin question từ file xml theo cấu trúc:
		String ques = "";
		p.addParam("question", ques);
		p.addParam("idupdatetype", idupdatetype);
		_peer.SendUpdateQuestion(addr, p);
	}
	public static void ReceiveRequestQuestion(JSONObject params, Address sender)
	{
		//nhận thông tin yêu cầu từ user khác
		//kiểm tra xem có thông tin phù hợp? --> có --> gửi phản hồi
		Log.d("PEERDROID","vao ham nhan ReceiveRequestSubject");
		Iterator<String> iter = params.keys();
		ArrayList<ArrayList<Object>> resList = new ArrayList<ArrayList<Object>>();
		int id = 0;
		int idQuestion = 0;
		int idUpdateType = 0;
		while(iter.hasNext()){
			String key = iter.next();
			String s = null;
			try {
				s = params.get(key).toString();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(key.equals("id"))
			{
				id = Integer.valueOf(s);
			}
			else if(key.equals("idquestion"))
			{
				idQuestion = Integer.valueOf(s);
			}
			else if(key.equals("idupdatetype"))
			{
				idUpdateType = Integer.valueOf(s);
			}
		}
		//kiểm tra:
		UpdateListDAO ulDao = new UpdateListDAO(null);
		boolean active = ulDao.getActive(id);
		if(active)
		{
			String address = sender.getHost() + ":" + sender.getPort();
			SendUpdateQuestion(address, idQuestion, idUpdateType);
		}
	}
	public static void SendRequestQuestion(String address, int id, int idquestion, int idupdate)
	{
		Payload p = new Payload();
		Address addr = new Address(address);
		//to do something
		p.addParam("idupdatetype", idupdate);
		p.addParam("idquestion", idquestion);
		p.addParam("id", id);

		_peer.SendRequestQuestion(addr, p);
	}

	/*-----------------------Các hàm module 4-----------------------------------------*/

	/*---------------------------Các hàm hệ thống học cộng tác---------------------------*/
	/**
	 * Hàm nhận thông tin yêu cầu tạo group của người dạy
	 * @param params
	 * @throws JSONException 
	 */
	public static void ReceiveGroupInvite(JSONObject params) throws JSONException
	{
		Iterator<String> iter = params.keys();
		long time=0;
		int nummember = 0;
		long closegroup = 0;
		while(iter.hasNext()){
			String key = (String) iter.next();

			if(key.equals("time"))
			{
				time = params.getLong(key);
			}
			else if(key.equals("nummember"))
			{
				nummember = params.getInt(key);
			}
			else if(key.equals("closegroup"))
			{
				closegroup = params.getLong(key);
			}
		}
		_isDoSearchGroup = true;
		ActivityController.ShowDialogReceiveGroupInvite(nummember, closegroup, time);

	}
	/**
	 * Hàm nhận bài tập nhóm của người dạy và xử lí
	 * @param params
	 * @throws JSONException 
	 * @throws NumberFormatException 
	 */
	public static void ReceiveExercisesGroup(JSONObject params) throws NumberFormatException, JSONException {
		// TODO Auto-generated method stub
		ExercisesGroupDTO exerciseList = new ExercisesGroupDTO();
		Iterator<String> iter = params.keys();
		ArrayList<CQuestion> questionList = new ArrayList<CQuestion>();
		ArrayList<String> arrquestioncontent = new ArrayList<String>();
		int idex = 0;
		int idPart = 0;
		int idDetail = 0;
		String title = "";
		String teamleader = "";
		while(iter.hasNext()){				
			String key = (String) iter.next();
			if(key.equals("iddetaillearning"))
			{
				idDetail = Integer.valueOf(params.get(key).toString());
				DetailLearningDAO dlDao = new DetailLearningDAO(null);
				idPart = dlDao.getIDPart(idDetail);
				exerciseList.setIDDetailLearning(idDetail);
				exerciseList.setIDPart(idPart);
			}
			else if(key.equals("title"))
			{
				title = params.get(key).toString();
				exerciseList.setNameExercises(title);
			}
			else if(key.equals("teamleader"))
			{
				teamleader = params.get(key).toString();
				exerciseList.setTeamLeader(teamleader);
			}
			else if(key.equals("idexercises"))
			{
				idex = params.getInt(key);
				exerciseList.setIDExercises(idex);
			}

			String s = params.get(key).toString();
			exerciseList.addQuestion(s);
			String[] sArr = s.split(SEPARATOR);
			if (sArr.length > 2) {
				for (String str : sArr)
					Log.d("PEERDROID", str);

				// XuatCauHoi(sArr);
				CQuestion ques = CQuestion.getQuestion(sArr);
				questionList.add(ques);
			}
		}
		String path = ReadWriteFileController.DIRECTORYTESTCONTENT + exerciseList.getIDPart()+"_" + exerciseList.getIDExercises() + "_GroupTest_" + exerciseList.getIDDetailLearning()+".xml";
		ReadWriteFileController.WriteExerciseGroup(path, exerciseList.getNameExercises(), exerciseList.getIDExercises(), idPart, exerciseList.getIDDetailLearning(), questionList);
		ReadWriteFileController.WriteTestListGroup(idPart, idDetail, idex, title);
		String pathList = "";
		//chỉ là teamleader mới nhận được gói tin rổng.
		if(teamleader.equals(""))//hv tự mời nhóm, gói tin này teamleader nhận
		{
			pathList = ReadWriteFileController.DIRECTORYCHATGROUP + "Group_" + _userName + "_ipList.xml";
			ArrayList<CMember> memList = ReadXML.ReadMember(pathList);
			SendQuestionGroup(exerciseList, memList);
		}
		else if(teamleader.equals(_userNameTeacher))//giáo viên tạo nhóm
		{
			pathList = ReadWriteFileController.DIRECTORYCHATGROUP + "Group_" + _userNameTeacher + "_grouping_ipList.xml";
			ArrayList<CMember> memList = ReadXML.ReadMember(pathList);
			SendQuestionGroup(exerciseList, memList);
		}
		else //hv tự mời nhóm, gói tin ngày các thành viên còn lại trong nhóm nhận
		{
			//ko làm j cả
		}
		_isDoExericseGroup = true;
		FrmViewExercise.set_idDetailLearning(idDetail);
		FrmViewExercise.set_idExericise(idex);
		FrmViewExercise.setIdPart(idPart);
		NotificationController.sendNotification(ActivityController.getPeerActivity().getBaseContext(), FrmViewExercise.class, "Thông báo", "Có bài tập làm nhóm!", Notification.DEFAULT_SOUND);
		//		ActivityController.ShowDialogReceiveExercisesGroup(exerciseList.getNameExercises());
	}
	/**
	 * Hàm lấy DS các nhóm tạo
	 * cấu trúc đầu ra : gồm nhiều phần tử, mỗi phần tử chứa user Create group
	 * @return
	 */
	public static ArrayList<String> LayDSGroup()
	{
		ArrayList<String> groupList = new ArrayList<String>();
		return groupList;
	}
	/**
	 * Hàm lấy ds user theo user tạo group
	 * cấu trúc mỗi list trong array : user, fullname, ip
	 * @param user
	 * @return
	 */
	public static ArrayList<ArrayList<Object>> LayDSDiaChiGroupTheoUser(String user)
	{
		ArrayList<ArrayList<Object>> temp = new ArrayList<ArrayList<Object>>();
		return temp;
	}
	/**
	 * Hàm gửi danh sách nhóm cho giáo viên
	 * @param arrDSGourp
	 * @param teamleader
	 */
	public static void SendListMemberToTeacher(int type){

		Payload p=new Payload("listmember");
		p.addParam("teamleader", _userName);
		String pathList = "";
		if(type == 1)//invite
			pathList = ReadWriteFileController.DIRECTORYCHATGROUP + "Group_" + _userName + "_ipList.xml";
		else if(type == 2)
			pathList = ReadWriteFileController.DIRECTORYCHATGROUP + "Group_" + _userNameTeacher + "_grouping_ipList.xml";
		ArrayList<CMember> memList = ReadXML.ReadMember(pathList);
		int i = 1;
		for(CMember mem : memList)
			p.addParam(""+ (i++),mem.get_userName() + SEPARATOR + mem.get_fullName() + SEPARATOR + mem.get_ip());  

		//gửi thông tin nhóm cho giáo viên
		_peer.SendListMember(new Address(_ipHost), p);
	}
	public static void sendFeedbackGroup(String content, String team, String filename, int port, int iddetaillearning, String title)
	{
		Payload p=new Payload("feedbackgroup");
		p.addParam("content", content);
		p.addParam("teamleader", team);
		p.addParam("portnumber", port);
		p.addParam("iddetaillearning", iddetaillearning);
		p.addParam("title", title);
		p.addParam("filename", filename);
		_peer.sendFeedbackGroup(new Address(_ipHost), p);
	}
	public static void SendQuestionGroup(ExercisesGroupDTO exGroup,  ArrayList<CMember> memList){

		Payload p=new Payload("exercisesgroup");
		p.addParam("iddetaillearning", exGroup.getIDDetailLearning());
		p.addParam("title", exGroup.getNameExercises());
		p.addParam("idexercises", exGroup.getIDExercises());
		p.addParam("teamleader", exGroup.getIDExercises());
		for(int i = 0;i<exGroup.getArrQuestion().size();i++)
		{
			p.addParam(""+ (i+1), exGroup.getArrQuestion().get(i).toString());
		}

		for(CMember mem : memList)
		{
			_peer.SendQuestionGroup(new Address(mem.get_ip()), p);
		}
	}

	/*-----------------------CÁc hàm khởi tạo-----------------------------------------*/
	public static void init(String name, int port)
	{
		_peer = new NetworkLayer(null,"4654amv65d4as4d65a4", name, port);
	}

	public static void set_peer(NetworkLayer _peer) {
		NetworkController._peer = _peer;
	}
	public static NetworkLayer get_peer() {
		return _peer;
	}
	public static void set_isLogin(int _isLogin) {
		NetworkController._isLogin = _isLogin;
	}
	public static int is_isLogin() {
		return _isLogin;
	}
	public static void set_userName(String _userName) {
		NetworkController._userName = _userName;
	}
	public static String get_userName() {
		return _userName;
	}
	public static void peerRelease()
	{
		_peer.halt();
	}
	public static void set_ipHost(String _ipHost) {
		NetworkController._ipHost = _ipHost;
	}
	public static String get_ipHost() {
		return _ipHost;
	}
	public static void set_idClass(int _idClass) {
		NetworkController._idClass = _idClass;
	}
	public static int get_idClass() {
		return _idClass;
	}
	public static void set_isOffline(boolean _isOffline) {
		NetworkController._isOffline = _isOffline;
	}
	public static boolean isOffline() {
		return _isOffline;
	}
	public static void set_idLearner(int _idLearner) {
		NetworkController._idLearner = _idLearner;
	}
	public static int get_idLearner() {
		return _idLearner;
	}

	public static void set_fullName(String _fullName) {
		NetworkController._fullName = _fullName;
	}

	public static String get_fullName() {
		return _fullName;
	}

	public static void set_ipUser(String _ipUser) {
		NetworkController._ipUser = _ipUser;
	}

	public static String get_ipUser() {
		return _ipUser;
	}

	public static String getSeparator1() {
		return SEPARATOR1;
	}

	public static String getSeparator() {
		return SEPARATOR;
	}

	public static void set_timedotest(int _timedotest) {
		NetworkController._timedotest = _timedotest;
	}

	public static int get_timedotest() {
		return _timedotest;
	}



	public static void set_runUpdateUserList(Runnable _runUpdateUserList) {
		NetworkController._runUpdateUserList = _runUpdateUserList;
	}

	public static Runnable get_runUpdateUserList() {
		return _runUpdateUserList;
	}

	public static void set_isWriteNeighborsList(boolean _isWriteNeighborsList) {
		NetworkController._isWriteNeighborsList = _isWriteNeighborsList;
	}

	public static boolean is_isWriteNeighborsList() {
		return _isWriteNeighborsList;
	}
	public static void set_isDoExericseGroup(boolean _isDoExericseGroup) {
		NetworkController._isDoExericseGroup = _isDoExericseGroup;
	}
	public static boolean is_isDoExericseGroup() {
		return _isDoExericseGroup;
	}
	public static void set_isDoSearchGroup(boolean _isDoSearchGroup) {
		NetworkController._isDoSearchGroup = _isDoSearchGroup;
	}
	public static boolean is_isDoSearchGroup() {
		return _isDoSearchGroup;
	}
	public static void set_isTeamLeader(boolean _isTeamLeader) {
		NetworkController._isTeamLeader = _isTeamLeader;
	}
	public static boolean is_isTeamLeader() {
		return _isTeamLeader;
	}

//===========teacher logout==================================
	
public static void ShowTeacherLogout(){
//	ActivityController.ShowDialogTeacherLogout();
	ActivityController.showMessageTeacherLogout();
}
public static void ShowDialogTeacherLogout(){
	ActivityController.ShowDialogTeacherLogout();
//	ActivityController.showMessageTeacherLogout();
}


}
